Ruby:基于标准调用方法
我有以下代码:Ruby:基于标准调用方法,ruby,criteria,case,switch-statement,Ruby,Criteria,Case,Switch Statement,我有以下代码: class Engine attr_accessor :isRunning def initialize @isRunning = false @commands = ["left", "right", "brake", "accelerate", "quit"] end def start self.isRunning = true; while(self.isRunning) command = gets.cho
class Engine
attr_accessor :isRunning
def initialize
@isRunning = false
@commands = ["left", "right", "brake", "accelerate", "quit"]
end
def start
self.isRunning = true;
while(self.isRunning)
command = gets.chomp!
if(@commands.include? command)
puts "OK."
else
puts "> #{command} Unknown Command."
end
if(command=="quit") then
self.stop
puts "Quitting!"
end
end
end
def stop
self.isRunning = false;
end
end
正如您所看到的,这非常简单,但是,我正在尝试找出如何根据条件调用方法。如果我在Engine类中实现一组方法,比如methodOne和MethodII,如下所示:
@commands = ["left", "right", "brake", "accelerate", "quit", "methodOne", "methodTwo"]
def methodOne
end
def methodTwo
end
def parseCommand(command)
if(command=="methodOne") then
self.methodOne
end
if(command=="methodTwo") then
self.methodTwo
end
end
我可以最低限度地调用这些方法吗?现在,我不得不写一大堆if语句,如果可以更优雅地完成,我宁愿省略它的未来维护。使用self.send(“methodname”)
你可以在
您的代码可能如下所示:
class Engine
# ...code ...
def parseCommands(commands)
commands.each{|c_command| self.send(c_command) }
end
# ...code ...
end
@commands = ["left", "right", "brake", "accelerate", "quit", "methodOne", "methodTwo"]
engineInstance.parseCommands(@commands)
它不必是一个符号,也可以是一个字符串。@beerlington,我还以为它可以是一个字符串,直到我看了一眼文档,上面说“调用由符号标识的方法”。虽然它使用字符串工作…实际上,“符号”是参数的名称。它可以是一个符号、一个字符串或响应
到\u str
的类似字符串的对象。我看看能不能把文档弄清楚。惯用语:methodOne->method\u one。如果(条件)->如果条件。虽然正确,但几乎没有人使用“then”。