4

I am trying to do something like this. It is giving me an error, which I guess is because op is a string. Is it possible to convert a string of a math operator to be an operator?

def calc(op)
  a = 9
  b = 5
  a op b
end

p calc('-')
p calc('+')
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
obelus
  • 115
  • 1
  • 10
  • 1
    Thanks for correcting display of the code! – obelus Nov 01 '13 at 19:13
  • 2
    I concur with @Arup's answer, but would like to point out that you could replace his line `a.send(op,b)` with `eval "#{a} #{op} #{b}"`. If `op = '+'`, this becomes `eval "9 + 5"`, which would be `14`. Some advise that `eval` always be avoided, because it can be dangerous if a user has supplied the string that is sent to `eval`, but here I think it has pretty much the same effect as `a.send(op,b)`. Again, I'd use `send`. – Cary Swoveland Nov 01 '13 at 21:08
  • Possible duplicate of [Can I dynamically call a math operator in Ruby?](http://stackoverflow.com/questions/13060239/can-i-dynamically-call-a-math-operator-in-ruby) – user513951 Jan 12 '16 at 12:35

1 Answers1

12

Here it is using Object#send:

def calc(op)
  a = 9
  b = 5
  a.send(op,b)
end

p calc('-')
p calc('+')
# >> 4
# >> 14
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317