使用用户输入调用方法(使用其字符串)

时间:2017-11-08 23:46:54

标签: ruby

我试图使用变量中的String来调用程序中的Method。

如何使用Variable中的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

1 个答案:

答案 0 :(得分: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