cod*_*ver 2 ruby design-patterns
可能重复:
如何将字符串转换为方法调用?
目前我有一个代码正在做这样的事情
def execute
case @command
when "sing"
sing()
when "ping"
user_defined_ping()
when "--help|-h|help"
get_usage()
end
Run Code Online (Sandbox Code Playgroud)
我发现这个案例非常无用且非常庞大,我只想通过使用变量@command调用适当的方法.就像是:
def execute
@command()
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我不需要和额外的execute()方法.
关于如何实现这款红宝石的任何建议?
谢谢!
编辑:为多个字符串添加了其他方法类型.不确定是否也可以优雅地处理.
退房发送
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3127 次 |
| 最近记录: |