How to convert the symbol of a mathematical operator to perform its operation?

I am trying to do something like this. This gives me an error, which I think because opis a string. Is it possible to convert a math operator string to an operator?

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

p calc('-')
p calc('+')
+4
source share
1 answer

Used here Object#send:

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

p calc('-')
p calc('+')
# >> 4
# >> 14
+11
source

All Articles