【发布时间】:2011-03-05 17:08:58
【问题描述】:
我有以下代码:
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 和 methodTwo,如下所示:
@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 语句,如果可以更优雅地完成,我宁愿省略它的未来维护。
【问题讨论】:
-
惯用语:methodOne -> method_one。如果(条件)-> 如果条件。而且,虽然正确,但几乎没有人使用“then”。
标签: ruby criteria case switch-statement