Abdul Ahmad Abdul Ahmad - 6 months ago 9
Ruby Question

ruby how to pass a method and invoke it with parameter

I tried to do the following in ruby, but it didn't work:

method_map = {
'one' => one
}
def one(param)
puts param
end

method_map['one']('hi')


then I realized that in ruby this will invoke the method before I even put parentheses, so I found out that I can pass a method name instead

method_map = {
'one' => :one
}
method_map['one']('hi')


but it still doesn't work. What's the correct way of passing a method, and then invoking it with a parameter in ruby?

Answer

One way of doing it as follows using send

2.2.2 > send(method_map['one'], 'hi')
=> hi

Using call

2.2.2 > method(method_map['one']).call('hi')
=> hi

You can also use eval (not recommended)

2.2.2 > eval "#{method_map['one']}('hi')"
=> hi

Benchmark (1 million iterations)

       user     system      total        real
send  0.670000   0.000000   0.670000 (  0.668050)
call  0.230000   0.000000   0.230000 (  0.225053)
eval  4.920000   0.000000   4.920000 (  4.919729)