define sum function in Ruby

2019-08-09 02:10发布

问题:

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.

回答1:

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


回答2:

Use array sum method.

arr = [1,2,3]
arr.sum


def sum(arr)
  arr.sum
end


回答3:

This will do:

def sum(array)
  array.reduce(0, :+)
end


回答4:

def sum(arr)
 sum = 0
 arr.each{|element| sum=sum+element }
 return sum
end