2

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:

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.

Community
  • 1
  • 1
codeObserver
  • 6,521
  • 16
  • 76
  • 121
  • Duplicate of http://stackoverflow.com/questions/4800836/call-a-method-on-a-variable-where-the-method-name-is-in-another-variable and http://stackoverflow.com/questions/6317298/how-to-turn-a-string-into-a-method-call and probably many others – millimoose Sep 30 '11 at 20:52

2 Answers2

5

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
Lee Jarvis
  • 16,031
  • 4
  • 38
  • 40
1

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
prekageo
  • 358
  • 3
  • 15