0
describe Array do
describe "#sum" do
it "has a #sum method" do
expect([]).to respond_to(:sum)
end
it "should be 0 for an empty array" do
expect([].sum).to eq(0)
end
it "should add all of the elements" do
expect([1,2,4].sum).to eq(7)
end
end
end
上面的代码是给我的测试代码。并且我将下面的代码用测试代码进行测试。我认为它会返回总数7.(1 + 2 + 4 = 7),但它返回0 ...我想它不会把[1,2,4]数组作为参数。我究竟做错了什么?Ruby方法没有得到数组参数
非常感谢你!真棒回答:-) – gin85
我还有一个问题,如果你不介意。所以你说它已经初始化了,如果我只想得到[1,2,4]数组本身呢?我怎样才能访问它? (在上面的答案中,'x'如何得到数组[1,2,4]? – gin85
在上面的例子中,'self'是引用数组。 'def sum'是一个实例方法,指的是数组的实例 - 在这种情况下[1,2,4] 什么注入基本上定义sum = 0;然后遍历数组(x始终是数组中的一个元素)。 – trueunlessfalse