Is there a better way to invoke methods?

I'm writing a simple script and need to shoot off methods based on
user input via ARGV. I'm trying to avoid the if, elseif chain, so
right now I'm using send...

h = {
"a" => :add,
"d" => :display
#etc
}
#other code
my_obj.send(h[user_input], parameters)

I'm just wondering if there is a more common practice for this sort of thing.
Todd

Another approach would be to replace the symbols in the Hash by
lambdas and invoke them.

h= {
  "a" => lambda {|p1, p2, p3| ...},
  "d" => lambda {|p1, p2, p3| ...},
}

h[user_input][parameters]
h[user_input].call(parameters)

Note though that in this case the object is missing. You could
include that in the closures though.

Kind regards

robert

···

On Wed, Oct 24, 2012 at 7:44 PM, Todd Benson <caduceass@gmail.com> wrote:

I'm writing a simple script and need to shoot off methods based on
user input via ARGV. I'm trying to avoid the if, elseif chain, so
right now I'm using send...

h = {
"a" => :add,
"d" => :display
#etc
}
#other code
my_obj.send(h[user_input], parameters)

I'm just wondering if there is a more common practice for this sort of thing.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Ideal. Thank you.

Todd

···

On Wed, Oct 24, 2012 at 1:37 PM, Robert Klemme <shortcutter@googlemail.com> wrote:

On Wed, Oct 24, 2012 at 7:44 PM, Todd Benson <caduceass@gmail.com> wrote:

I'm writing a simple script and need to shoot off methods based on
user input via ARGV. I'm trying to avoid the if, elseif chain, so
right now I'm using send...

Another approach would be to replace the symbols in the Hash by
lambdas and invoke them.

h= {
  "a" => lambda {|p1, p2, p3| ...},
  "d" => lambda {|p1, p2, p3| ...},
}

h[user_input][parameters]
h[user_input].call(parameters)

Note though that in this case the object is missing. You could
include that in the closures though.

Kind regards

robert