Reputation: 309
I am trying to write a small function with ruby that gets fed a array from the user and then sums up the data in the array. I have written it as
def sum(a)
total = 0
a.collect { |a| a.to_i + total }
end
The function then runs through a rspec, which tests it by initially feeding into it a blank array. This this causes the following error
sum computes the sum of an empty array
Failure/Error: sum([]).should == 0
expected: 0
got: [] (using ==)
So its telling me that when it feeds the blank array in, its supposed to get 0 but instead its getting the array. I tried putting in a if statement written as
def sum(a)
total = 0
a.collect { |a| a.to_i + total }
if total = [] then { total = 0 end }
end
but it gives me an error saying
syntax error, unexpected '}', expecting => (SyntaxError)
what am I doing wrong?
Upvotes: 0
Views: 1692
Reputation: 230336
You shouldn't use map
/collect
for this. reduce
/inject
is the appropriate method
def sum(a)
a.reduce(:+)
# or full form
# a.reduce {|memo, el| memo + el }
# or, if your elements can be strings
# a.map(&:to_i).reduce(:+)
end
Upvotes: 2
Reputation: 27247
See here: How to sum array of numbers in Ruby?
and here: http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject
def sum(a)
array.inject(0) {|sum,x| sum + x.to_i }
end
Upvotes: 0