【问题标题】:Calling a method using the string/variable of the method name inRuby [duplicate]使用Ruby中方法名称的字符串/变量调用方法[重复]
【发布时间】:2011-09-30 20:49:15
【问题描述】:

可能重复:
How to turn a string into a method call?

目前我有一个代码正在做这样的事情

def execute
  case @command
    when "sing"
      sing()
    when "ping"
      user_defined_ping()
    when "--help|-h|help"
      get_usage()      
end

我发现这个案例非常无用而且很大,我想通过使用变量@command 来调用适当的方法。比如:

def execute
 @command()
end

当然,在这种情况下,我不需要额外的 execute() 方法。

关于如何获得这颗红宝石的任何建议?

谢谢!

编辑: 为多个字符串添加了其他方法类型。不确定这是否也可以优雅地处理。

【问题讨论】:

标签: ruby design-patterns


【解决方案1】:

查看send

send(@command) if respond_to?(@command)

respond_to? 确保 self 在尝试执行此方法之前对其作出响应

对于更新后的get_usage() 部分,我会使用类似的内容:

def execute
  case @command
  when '--help', '-h', 'help'
    get_usage()
  # more possibilities
  else
    if respond_to?(@command)
      send(@command)
    else
      puts "Unknown command ..."
    end
  end
end

【讨论】:

  • 漂亮!! thnkx @injekt ..我在问题中添加的 get_usage() 方法还有什么吗?
【解决方案2】:

您可能正在寻找send。看看这个:http://ruby-doc.org/core/classes/Object.html#M000999

def execute
    send @command
end

【讨论】:

    猜你喜欢
    • 2010-11-27
    • 2017-07-16
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多