r/learnruby • • 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

4 comments sorted by

View all comments

Show parent comment

1

u/materialdesigner May 05 '14

I mean you could literally do that exact same thing in ruby I'd just question why you ever wanted to do that lol.