method
sum
Ruby latest stable (v2_5_5)
-
0 notes -
Class: Enumerable
- 1_8_6_287
- 1_8_7_72
- 1_8_7_330
- 1_9_1_378
- 1_9_2_180
- 1_9_3_125
- 1_9_3_392
- 2_1_10
- 2_2_9
- 2_4_6 (0)
- 2_5_5 (0)
- 2_6_3 (0)
- What's this?
sum(p1 = v1)
public
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:
{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50 (1..10).sum #=> 55 (1..10).sum {|v| v * 2 } #=> 110 [Object.new].each.sum #=> TypeError
This method can be used for non-numeric objects by explicit init argument.
{ 1 => 10, 2 => 20 }.sum([]) #=> [1, 10, 2, 20] "a\nb\nc".each_line.lazy.map(&:chomp).sum("") #=> "abc"
Enumerable#sum method may not respect method redefinition of “+” methods such as Integer#+.