r/learnruby • u/JohnnyRingolevio • May 04 '14
Writing a calculator with classes
Hey everyone, thanks in advance for taking a look at this. My question is related to sending input through a simple calculator Class that I've built. A sample is as follows:
class Calculator
def initialize(num1, num2, op)
@num1 = num1
@num2 = num2
@op = op
end
def addition
if @op == "+"
sum = @num1 + @num2
end
puts sum
end
end
p calc = Calculator.new(2, 5, '+')Of course, this is not working as intended, I know that there is a way to do this with a switch statement in C++ (parsing out what function to go to based on the operand) but I am slightly confused as to how to parse input through definitions in by a class in Ruby. Any tips would be really appreciated.
2
Upvotes
View all comments
Show parent comment
1
u/JohnnyRingolevio May 05 '14
Thank you very much for your detailed reply. I really appreciate it, there is a lot of food for thought here.
I am sure that my object design in this instance is probably pretty bad. My attempt in doing this was to try and relate what (little) I know about C++ to Ruby through finding similarities with Functions (C++) and Methods (Ruby); which I understand are not completely interchangeable but have a little bit of theoretical overlap.
Essentially, in C++ you could write a function for addition that would perform the task of summing the numbers and return those two numbers, and this could be implemented if the user entered + in the equation (via a switch statement). E.G.
}
However, I am beginning to think that trying to make this type of connection is more of a hindrance than helpful. I suppose sometimes you have to forget in order to learn something new... (And in my case a little bit of knowledge can be very dangerous).