Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass operator as a parameter in ruby?

Tags:

ruby

Here is what I have:

operator = '>'

Here is what I tried:

5 operator.to_sym 4

#invalid result => 
5 :>= 4 

Expected: 5 > 4

like image 637
Prashanth Sams Avatar asked Apr 21 '26 16:04

Prashanth Sams


1 Answers

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)
like image 199
Sebastian Palma Avatar answered Apr 24 '26 07:04

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!