Reputation: 41
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
end
p calculator(4,'+',5)
I keep getting error messages. Please advise on how to call a different operator to complete this.
Upvotes: 0
Views: 1819
Reputation: 798
You should read about what is method signature and what is switch statement.
If you don't want to bother with understanding you can use ruby send method.
EDIT: How to define method in Ruby
Upvotes: -2
Reputation: 106802
Perhaps something like:
def calculator(a, operation, b)
a.send(operation, b)
end
calculator(1, '+', 3)
#=> 4
calculator(3, '*', 2)
#=> 6
Upvotes: 6