【问题标题】:Ruby: invoking methods based on criteriaRuby:基于标准调用方法
【发布时间】: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


【解决方案1】:

使用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)

【讨论】:

  • 不一定是符号,也可以是字符串。
  • @beerlington,我还认为它可能是一个字符串,直到我查看文档告诉“调用由符号标识的方法”。虽然它使用字符串...
  • 其实“符号”就是参数的名称。它可以是响应to_str 的符号、字符串或类似字符串的对象。我看看能不能把文档写的更清楚。
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 2016-02-29
  • 2012-03-09
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
相关资源
最近更新 更多