我的准备工作是要求我制作一个数组扩展文件,然后向其中添加一些方法。这是他们给我的:
describe Array do
describe "#sum" do
it "has a #sum method" do
[].should respond_to(:sum)
end
it "should be 0 for an empty array" do
[].sum.should == 0
end
it "should add all of the elements" do
[1,2,4].sum.should == 7
end
end
end
所以我写了这个:
class Array
def sum(array = [])
add = 0
if array == []
array = add
else
while array.length > 0
add = add + array.last
array.pop
end
array = add
end
array
end
end
我不断收到此错误:
Array #sum
has a #sum method
should be 0 for an empty array
should add all of the elements (FAILED - 1)
Failures:
1) Array#sum should add all of the elements
Failure/Error: [1,2,4].sum.should == 7
expected: 7
got: 0 (using ==)
# ./14_array_extensions/array_extensions_spec.rb:23:in `block (3 levels) in <top (required)>'
Finished in 0.00241 seconds 3 examples, 1 failure
谢谢你的时间。