简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM