Ruby Array Extension -
my prep work asking me make array extension file , add methods it. gave me:
describe array describe "#sum" "has #sum method" [].should respond_to(:sum) end "should 0 empty array" [].sum.should == 0 end "should add of elements" [1,2,4].sum.should == 7 end end end
so i've written this:
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
i keep getting error:
array #sum has #sum method should 0 empty array should add of elements (failed - 1) failures: 1) array#sum should add of 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
thanks time.
extending array
means should using self
rather passing in array. right now, you're summing empty array (from default parameter) rather array #sum
called on.
Comments
Post a Comment