问题
Based on the Ruby Monk Calculator exercise, I was trying to build a simple calculator that can add and subtract:
class Calculator
def add(a,b)
a + b
end
def subtract(a,b)
a - b
end
end
puts "input first integer"
a = gets.chomp.to_i
puts "input second integer"
b = gets.chomp.to_i
puts "add or subtract?"
response = gets.chomp.downcase
if response == "add"
Calculator.add(a,b)
else response == "subtract"
Calculator.subtract(a,b)
end
When I run the code, I keep getting the 'NoMethodError' - the methods 'add' and 'subtract' are undefined. I don't understand why I'm getting this error, and wondering if I'm calling the method wrong.
回答1:
You defined your methods at the instance level, rather than the class level. Either use
def self.add(a,b)
a + b
end
or create an instance of Calculator
calc = Calculator.new
calc.add(a,b)
来源:https://stackoverflow.com/questions/31331287/no-method-error-ruby-calculator