在Ruby中定义sum函数 [英] define sum function in Ruby

查看:113
本文介绍了在Ruby中定义sum函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮忙,我是一名Ruby学生,我知道如何做.sum方法,但不知道如何:
如何定义一个数组的求和函数,以便提供任何元素将导致他们。格式应该是sum([array inputs])返回数组元素的总和。例如:sum([])应该返回0,sum([1,2,3])返回6(#again,不是[1,2,3] .sum)。我被困在盒子里,非常感谢你的帮助。 使用

html#method-i-injectrel =nofollow> Enumerable#inject

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆