简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM