Please bear in mind that I am fairly new to Ruby. I am currently following a tutorial that is asking me to create a basic calculator. I need to create a Calculator class, that has the following methods; description, add, subtract, multiply and divide.
My initialize method can successfully take two numbers, but I can't seem to get the other methods working.
Here is my code:
class Calculator
attr_accessor :x, :y
def self.description
"Performs basic mathematical operations"
end
def initialize(x, y)
@x = x
@y = y
end
def add(x, y)
x += y.to_i
end
def subtract(x, y)
x -= y.to_i
end
end
I am getting "wrong number of arguments (0 for 2)"
The code is correct, but it doesn't make a lot of sense. You are passing the values to the initializer, therefore I expect your code to be used as it follows
c = Calculator.new(7, 8)
c.add
# => 15
and it's probably the way you are calling it. However, this is not possible because you defined add() to take two arguments. Therefore, you should use
c = Calculator.new(7, 8)
c.add(1, 2)
# => 3
But then, what's the point of passing x and y to the initializer? The correct implementation is either
class Calculator
attr_accessor :x, :y
def self.description
"Performs basic mathematical operations"
end
def initialize(x, y)
@x = x.to_i
@y = y.to_i
end
def add
x + y
end
def subtract
x - y
end
end
or more likely
class Calculator
def self.description
"Performs basic mathematical operations"
end
def initialize
end
def add(x, y)
x.to_i + y.to_i
end
def subtract(x, y)
x.to_i - y.to_i
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With