在Ruby中定义sum函数 [英] define sum function in Ruby
问题描述
请帮忙,我是一名Ruby学生,我知道如何做.sum方法,但不知道如何: html#method-i-injectrel =nofollow> Enumerable#inject
如何定义一个数组的求和函数,以便提供任何元素将导致他们。格式应该是sum([array inputs])返回数组元素的总和。例如:sum([])应该返回0,sum([1,2,3])返回6(#again,不是[1,2,3] .sum)。我被困在盒子里,非常感谢你的帮助。 使用
def sum(array )
array.inject(0){| sum,el |或者,按照建议,更短更优雅的形式:
$ / code>
def sum(array)
array.inject(0,:+)
end
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.
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
这篇关于在Ruby中定义sum函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!