Three Ways: send
/ call
/ eval
- and their Benchmarks
Typical invocation (for reference):
s= "hi man"
s.length #=> 6
Using send
s.send(:length) #=> 6
Using call
method_object = s.method(:length)
p method_object.call #=> 6
Using eval
eval "s.length" #=> 6
Benchmarks
require "benchmark"
test = "hi man"
m = test.method(:length)
n = 100000
Benchmark.bmbm {|x|
x.report("call") { n.times { m.call } }
x.report("send") { n.times { test.send(:length) } }
x.report("eval") { n.times { eval "test.length" } }
}
...as you can see, instantiating a method object is the fastest dynamic way in calling a method, also notice how slow using eval is.
#######################################
##### The results
#######################################
#Rehearsal ----------------------------------------
#call 0.050000 0.020000 0.070000 ( 0.077915)
#send 0.080000 0.000000 0.080000 ( 0.086071)
#eval 0.360000 0.040000 0.400000 ( 0.405647)
#------------------------------- total: 0.550000sec
# user system total real
#call 0.050000 0.020000 0.070000 ( 0.072041)
#send 0.070000 0.000000 0.070000 ( 0.077674)
#eval 0.370000 0.020000 0.390000 ( 0.399442)
Credit goes to this blog post which elaborates a bit more on the three methods and also shows how to check if the methods exist.