Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a math operator character to perform its operation?

Tags:

ruby

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('+')
like image 738
obelus Avatar asked Dec 15 '22 04:12

obelus


1 Answers

Here it is using Object#send:

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

p calc('-')
p calc('+')
# >> 4
# >> 14
like image 74
Arup Rakshit Avatar answered Jan 29 '23 21:01

Arup Rakshit