As far as I am aware there are three ways to dynamically call a method in Ruby:
Method 1:
s = SomeObject.new
method = s.method(:dynamic_method)
metho
I updated the benchmark from @Stefan to check if there are some speed improvements when saving reference to method. But again – send is much faster than call
require 'benchmark'
class Foo
def bar; end
end
foo = Foo.new
foo_bar = foo.method(:bar)
Benchmark.bm(4) do |b|
b.report("send") { 1_000_000.times { foo.send(:bar) } }
b.report("call") { 1_000_000.times { foo_bar.call } }
end
These are the results:
user system total real
send 0.080000 0.000000 0.080000 ( 0.088685)
call 0.110000 0.000000 0.110000 ( 0.108249)
So send seems to be the one to take.