Art_Vandelay17 Art_Vandelay17 - 9 months ago 97
Ruby Question

Calculation method in ruby

I need to write a calculate method that takes three parameters: an integer, an operator string (example: "+"), and another integer. The method should execute the operation and return the result, an integer. The method should be able to handle the +, -, *, and / operations. For example, calculate(4, '+', 5) should return 9.

I think the method should be something like this:

def calculator(a,'b',c)
a.to_i b.to_s c.to_i

p calculator(4,'+',5)

I keep getting error messages. Please advise on how to call a different operator to complete this.


Perhaps something like:

def calculator(a, operation, b)
  a.send(operation, b)

calculator(1, '+', 3)
#=> 4
calculator(3, '*', 2)
#=> 6