Possible Duplicate:
How to turn a string into a method call?可能重复:如何将字符串转换为方法调用?
Currently I have a code that is doing something like this
目前我有一个类似这样的代码
def execute
case @command
when "sing"
sing()
when "ping"
user_defined_ping()
when "--help|-h|help"
get_usage()
end
I find the case pretty useless and huge and I had like to call the appropriate method just by using the variable @command. Something like:
我发现这个例子非常无用,而且很大,我喜欢通过使用变量@command调用适当的方法。喜欢的东西:
def execute
@command()
end
Offcourse I would not need and extra execute() method in this case.
当然,在这种情况下,我不需要和额外的execute()方法。
Any suggestions on how I can acheive this ruby ?
关于如何完成这个ruby有什么建议吗?
Thanks!
谢谢!
Edit: Added other method type for multiple strings. Not sure if that can also be handled in an elegant manner.
编辑:为多个字符串添加其他方法类型。不确定这是否也能以一种优雅的方式处理。
2 个解决方案
#1
5
Check out send
查看发送
send(@command) if respond_to?(@command)
发送(@command)如果respond_to ?(@command)
The respond_to?
ensures that self
responds to this method before attempting to execute it
respond_to吗?确保self在尝试执行此方法之前对其做出响应
For the updated get_usage()
part I would use something similar to this:
对于更新后的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
#2
1
You are looking for send
probably. Take a look at this: http://ruby-doc.org/core/classes/Object.html#M000999
您可能正在寻找发送。看看这个:http://ruby-doc.org/core/classes/Object.html#M000999
def execute
send @command
end
#1
5
Check out send
查看发送
send(@command) if respond_to?(@command)
发送(@command)如果respond_to ?(@command)
The respond_to?
ensures that self
responds to this method before attempting to execute it
respond_to吗?确保self在尝试执行此方法之前对其做出响应
For the updated get_usage()
part I would use something similar to this:
对于更新后的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
#2
1
You are looking for send
probably. Take a look at this: http://ruby-doc.org/core/classes/Object.html#M000999
您可能正在寻找发送。看看这个:http://ruby-doc.org/core/classes/Object.html#M000999
def execute
send @command
end