2015-07-10 60 views
1

基於Ruby的僧計算器鍛鍊,我想建立一個簡單的計算器,可以加減:沒有方法錯誤 - 紅寶石計算器

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 

當我運行代碼,我不斷收到「NoMethodError ' - 方法'add'和'subtract'未定義。我不明白爲什麼我得到這個錯誤,並想知道我是否調用了錯誤的方法。

回答

4

您在實例級而不是類級別定義了您的方法。要麼使用

def self.add(a,b) 
    a + b 
end 

或創建的Calculator

calc = Calculator.new 
calc.add(a,b) 
+0

謝謝您的回答一個實例! – mjjcha