Prashanth Sams
Prashanth Sams

Reputation: 21129

How to pass operator as a parameter in ruby?

Here is what I have:

operator = '>'

Here is what I tried:

5 operator.to_sym 4

#invalid result => 
5 :>= 4 

Expected: 5 > 4

Upvotes: 3

Views: 754

Answers (2)

Sebastián Palma
Sebastián Palma

Reputation: 33420

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)

Upvotes: 8

Mark
Mark

Reputation: 6445

Check out Ruby string to operator - you need to use public send:

operator = '>'
5.public_send(operator, 4)
=> true
operator = '-'
5.public_send(operator, 4)
=> 1

Upvotes: 3

Related Questions