2017-11-08 6 views
-1

変数内のStringを使用して、プログラム内のメソッドを呼び出そうとしています。ユーザーの入力を使用してメソッドを呼び出す(文字列を使用)

変数の文字列を使用して、複数のチェックを入れ子にしたり、複数のチェックをしなくても、メソッドを呼び出すにはどうすればよいですか?

module Player 
    @@location = "location" 

    def Player.input(input) 
    if input == "look" 
     "Call Method from @@location" 
    end 
    end 

    def Player.set_location(input) 
    @@location = input 
    end 
end 

def input 
    print "> " 
    Player.input(@stdin.gets.chomp) 
end 

def "name of Method can be same as @@location" 
    ... 
end 

def "another name of Method can be same as @@location" 
    ... 
end 

def "another name, etc" 
    ... 
end 
+0

あなたは([オブジェクト#センド]を探しているhttps://ruby-doc.org/core -2.4.2/Object.html#method-i-send)? – itdoesntwork

+1

あなたの質問は非常に不明です。あなたの質問のタイトル、最初のパラグラフ、そして2番目のパラグラフでは、*メソッドを呼び出すことについて尋ねますが、コードで*定義する*メソッドの例を示します。また、メソッドの名前は '@@ location'と同じであり、メソッドの名前は' @@ location'と同じですが意味がありません。両方の名前が '@@ location'の場合、両方の名前は同じです。言い換えれば、*ただ一つの名前*があり、"別の名前 "はありません。 –

+1

これらのルール、コーナーケース、特殊ケース、境界ケース、エッジケースからの例外を含む、すべてのルールを含めて、実行したいことを*正確に指定できますか?通常のケースと例外、コーナーケース、特殊ケース、境界ケース、エッジケースの両方で、起こりそうなことを示すサンプル入力と出力を提供できますか? –

答えて

0

あなたが巣することなく、とはどういう意味ですか?私はあなたのコードが人為的な例であるのだろうかと思います。特別なオブジェクトmainでメソッドを定義すると、mainからも呼び出された場合、クイックテストで問題ありません。そうでない場合はクラスに入れる必要があります。

だから、答えはそのような単純なものでした:

module Player 
    @location = 'location' 

    def Player.input(input) 
    puts "in Player.input(#{input})" 
    if input == 'look' 
     puts "Calling method <#{@location}>" 
     Switch.send(@location) 
    else 
     puts 'wrong input, must be "look"' 
    end 
    end 

    def Player.set_location(input) 
    @location = input 
    end 
end 

def input 
    print "> " 
    Player.input(gets.chomp) 
end 

class Switch 
    def self.abc 
     puts 'in abc' 
    end 

    def self.def 
     puts 'in def' 
    end 

    def self.location 
     puts 'in location' 
    end 

    def self.method_missing(name, *args, &block) 
     puts "There is no method #{name} in #{self.name}" 
    end 
end 

input 
input 
Player.set_location('abc') 
input 
Player.set_location('xyz') 
input 

実行:

$ ruby -w t.rb 
> looc 
in Player.input(looc) 
wrong input, must be "look" 
> look 
in Player.input(look) 
Calling method <location> 
in location 
> look 
in Player.input(look) 
Calling method <abc> 
in abc 
> look 
in Player.input(look) 
Calling method <xyz> 
There is no method xyz in Switch 
+0

これはまさに私が探していたものです!ありがとうございました! –

関連する問題