使用Ruby中方法名称的字符串/变量调用方法

使用Ruby中方法名称的字符串/变量调用方法,ruby,design-patterns,Ruby,Design Patterns,可能重复: 目前,我有一个代码正在做类似的事情 def execute case @command when "sing" sing() when "ping" user_defined_ping() when "--help|-h|help" get_usage() end 我发现这个案例非常无用和庞大,我只想通过使用变量@command调用适当的方法。比如: def execute @command() end

可能重复:

目前,我有一个代码正在做类似的事情

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()方法

有没有关于我如何获得这个红宝石的建议

谢谢

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

您可能正在寻找
send
。看看这个:

退房

如果响应(@command)则发送(@command)

respond\u 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()方法是否也有一些内容?
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