Calling a method using the string/variable of the method name inRuby [duplicate]
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 var开发者_StackOverflowiable @command. Something like:
def execute
@command()
end
Offcourse I would not need and extra execute() method in this case.
Any suggestions on how I can acheive this ruby ?
Thanks!
Edit: Added other method type for multiple strings. Not sure if that can also be handled in an elegant manner.
Check out send
send(@command) if respond_to?(@command)
The respond_to?
ensures that self
responds to this method before attempting to execute it
For the updated get_usage()
part I would use something similar to this:
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
You are looking for send
probably. Take a look at this: http://ruby-doc.org/core/classes/Object.html#M000999
def execute
send @command
end
精彩评论