开发者

Calling a method using the string/variable of the method name inRuby [duplicate]

开发者 https://www.devze.com 2023-04-10 09:56 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to turn a string into a method call?
This question already has answers here: Closed 11 years ago.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号