No Method Error - Ruby Calculator

蹲街弑〆低调 提交于 2021-01-28 19:55:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!