我有一个整数数组。

例如:

array = [123,321,12389]

有什么好方法能求出它们的和吗?

我知道

sum = 0
array.each { |a| sum+=a }

是可行的。


当前回答

Ruby 2.4+ / Rails -数组。和即[1,2,3]。Sum # =>

Ruby pre 2.4 - array.inject(:+)或array.reduce(:+)

*注意:#sum方法是2.4中用于枚举的新添加,所以你现在可以使用数组了。sum是纯ruby,而不仅仅是Rails。

其他回答

Ruby 2.4.0新增功能

您可以使用命名恰当的方法Enumerable#sum。与inject(:+)相比,它有很多优点,但在最后也有一些重要的注意事项需要阅读。

例子

范围

(1..100).sum
#=> 5050

数组

[1, 2, 4, 9, 2, 3].sum
#=> 21

[1.9, 6.3, 20.3, 49.2].sum
#=> 77.7

重要提示

这个方法不等同于#inject(:+)。例如

%w(a b c).inject(:+)
#=> "abc"
%w(a b c).sum
#=> TypeError: String can't be coerced into Integer

同时,

(1..1000000000).sum
#=> 500000000500000000 (execution time: less than 1s)
(1..1000000000).inject(:+)
#=> 500000000500000000 (execution time: upwards of a minute)

有关为什么sum是这样的更多信息,请参阅这个答案。

对于Ruby >=2.4.0,你可以使用sum from Enumerables。

[1, 2, 3, 4].sum

mokeypatch基类是很危险的。如果你喜欢危险并且使用旧版本的Ruby,你可以在Array类中添加#sum:

class Array
  def sum
    inject(0) { |sum, x| sum + x }
  end
end

你可以像这样使用。map和。sum:

array.map { |e| e }.sum

也允许[1,2]。Sum {|x| x * 2} == 6:

# http://madeofcode.com/posts/74-ruby-core-extension-array-sum
class Array
  def sum(method = nil, &block)
    if block_given?
      raise ArgumentError, "You cannot pass a block and a method!" if method
      inject(0) { |sum, i| sum + yield(i) }
    elsif method
      inject(0) { |sum, i| sum + i.send(method) }
    else
      inject(0) { |sum, i| sum + i }
    end
  end
end

只是为了多样性,如果你的数组不是一个数字数组,而是一个具有数字属性的对象数组(例如amount),你也可以这样做:

array.inject(0){|sum,x| sum + x.amount}