Art_Vandelay17 Art_Vandelay17 - 1 year ago 143
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.

Answer Source

Perhaps something like:

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

calculator(1, '+', 3)
#=> 4
calculator(3, '*', 2)
#=> 6
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download