2017-03-06 31 views
0
class Calculator 

def initialize 
    @array = Array.new 
    @total = 0 
end 

def push(n) 
    @array << n 
end 

def value 
    @total 
end 

def plus 
    size = @array.size 
    total = @array.pop(size) + @array.pop(size-1) 
    @array << total 
    @total = total 
end  
end 

和測試代碼是這個ruby代碼應該返回元素的總和,但只返回數組本身。

calculator = Calculator.new 
calculator.push(2) 
calculator.push(3) 
calculator.plus 
expect(calculator.value).to eq(5) 

我有望獲得 '5' 從 '值' 的方法。但它返回的是一個數組[2,3]。我做錯了什麼?

回答

1

用參數彈出返回一個數組。使用不帶參數的pop來獲取數字。

total = array + array 

因此,total變成了一個數組。

+0

哦我的!!非常感謝 :-) – gin85