End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#sum
enum.sum(init=0) → number
enum.sum(init=0) {|e| expr } → number
enum.c
View on GitHub ↗
static VALUE
enum_sum(int argc, VALUE* argv, VALUE obj)
{
struct enum_sum_memo memo;
VALUE beg, end;
int excl;
memo.v = (rb_check_arity(argc, 0, 1) == 0) ? LONG2FIX(0) : argv[0];
memo.block_given = rb_block_given_p();
memo.n = 0;
memo.r = Qundef;
if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
memo.f = RFLOAT_VALUE(memo.v);
memo.c = 0.0;
}
else {
memo.f = 0.0;
memo.c = 0.0;
}
if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
if (!memo.block_given && !memo.float_value &&
(FIXNUM_P(beg) || RB_TYPE_P(beg, T_BIGNUM)) &&
(FIXNUM_P(end) || RB_TYPE_P(end, T_BIGNUM))) {
return int_range_sum(beg, end, excl, memo.v);
}
}
if (RB_TYPE_P(obj, T_HASH) &&
rb_method_basic_definition_p(CLASS_OF(obj), id_each))
hash_sum(obj, &memo);
else
rb_block_call(obj, id_each, 0, 0, enum_sum_i, (VALUE)&memo);
if (memo.float_value) {
return DBL2NUM(memo.f + memo.c);
}
else {
if (memo.n != 0)
memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
if (memo.r != Qundef) {
memo.v = rb_rational_plus(memo.r, memo.v);
}
return memo.v;
}
}
Returns the sum of elements in an Enumerable.
If a block is given, the block is applied to each element before addition.
If enum is empty, it returns init.
For example:
Example
{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50
(1..10).sum #=> 55
(1..10).sum {|v| v * 2 } #=> 110
('a'..'z').sum #=> TypeError
This method can be used for non-numeric objects by explicit init argument.
Example
{ 1 => 10, 2 => 20 }.sum([]) #=> [1, 10, 2, 20]
"a\nb\nc".each_line.lazy.map(&:chomp).sum("") #=> "abc"
If the method is applied to an Integer range without a block, the sum is not done by iteration, but instead using Gauss’s summation formula.
Enumerable#sum method may not respect method redefinition of “+” methods such as Integer#+, or “each” methods such as Range#each.