Please help, I am a Ruby student, I know how to do the .sum method but not this: how do you define a sum function for an array so that providing any elements will result in the sum of them. The format should be sum([array inputs]) return sum of array elements. For ex: sum([ ]) should return 0, sum([1,2,3]) returns 6 (#again, not [1,2,3].sum). I am so stuck in the box, thank you very much for any help.
4 Answers
Solution with usage of Enumerable#inject:
def sum(array)
array.inject(0){|sum, el| sum + el}
end
Or, as suggested, shorter and more elegant form:
def sum(array)
array.inject(0, :+)
end
1 Comment
ovhaag
or
array.sum -- see answer from NikDPdef sum(arr)
sum = 0
arr.each{|element| sum=sum+element }
return sum
end
2 Comments
tokland
While this works, so imperative a way of doing thing is not idiomatic in Ruby (and that
return is definitely not idiomatic).Kim Jong Il
Thank you very much, this is more of my level :)
Array#sum:)summethod do you know? Are you mentioning Rails?