2011-09-30 75 views
2

可能重复:
How to turn a string into a method call?使用方法名的字符串/变量调用一个方法inRuby

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

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

我发现这个案子非常无用,而且我非常喜欢通过使用va来调用适当的方法riable @命令。喜欢的东西:

def execute 
@command() 
end 

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

有关我如何实现这个红宝石的任何建议?

谢谢!

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

+0

重复的http://stackoverflow.com/questions/4800836/call-a-method-on-a-variable-where-the-method-name-is-in-another-variable和http:// stackoverflow.com/questions/6317298/how-to-turn-a-string-into-a-method-call和其他许多 – millimoose

回答

6

退房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 
+0

美丽! thnkx @injekt ..还有一些我在问题中添加的get_usage()方法吗? – codeObserver

+0

我已经更新了我的答案 –