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
the code above is the test code given to me. and I made the code below to be tested by the test code.
class Array
def initialize(arr)
@arr = arr
end
def sum
if @arr == nil
return 0
else
numArr = @arr
total = 0
numArr.each {|num|
total += num
}
return total
end
end
end
I thought it would return total 7. (1+2+4 = 7) but it returns 0... I guess it doesn't take [1,2,4] array as a parameter. what am I doing wrong?