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)
method.call
Method 2:
s = SomeObject.new
s.send(:dynamic_method)
Method 3:
s = SomeObject.new
eval "s.dynamic_method"
By benchmarking them I have established that Method 1 is by far the fastest, Method 2 is slower, and Method 3 is by far the slowest.
I have also found that .call
and .send
both allow calling private methods, while eval
does not.
So my question is: is there any reason to ever use .send
or eval
? Why would you not always just use the fastest method? What other differences do these methods of calling dynamic methods have?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…