2017-03-06 3 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 

とテストコードがi 'は値' メソッドから '5' を取得することが期待このルビコードは、要素の合計を返しますが、配列自体を返すだけです。

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

あります。しかしそれは配列である[2,3]を返しています。どうしたんだ?

答えて

1

popを引数に指定すると、配列が返されます。引数なしでpopを使用すると、数値だけが得られます。

total = array + array 

したがって、合計は配列になります。

+0

oh my !!どうもありがとうございます :-) – gin85

関連する問題