Ruby:根据条件调用方法

时间:2011-03-05 17:08:59

标签: 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.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语句,如果可以更优雅地完成,我宁愿省略其未来的维护。

1 个答案:

答案 0 :(得分:3)

使用self.send("methodname")

您可以在Docs

中详细了解相关信息

您的代码可能如下所示:

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)