Here is what I have:
operator = '>'
Here is what I tried:
5 operator.to_sym 4
#invalid result =>
5 :>= 4
Expected:
5 > 4
You can use public_send or (send depending the method):
operator = :>
5.public_send(operator, 4)
# true
public_send (as send) can receive a method as String or Symbol.
In case the method you're using isn't defined in the object class, Ruby will raise a NoMethodError.
You can also do receiver.method(method_name).call(argument), but that's just more typing:
5.method(operator).call(4)
# true
Thanks @tadman for the benchmark comparing send and method(...).call:
require 'benchmark'
Benchmark.bm do |bm|
repeat = 10000000
bm.report('send') { repeat.times { 5.send(:>, 2) } }
bm.report('method.call') { repeat.times { 5.method(:>).call(2) } }
end
# user system total real
# send 0.640115 0.000992 0.641107 ( 0.642627)
# method.call 2.629482 0.007149 2.636631 ( 2.644439)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With