method
sum
v2_5_5 -
Show latest stable
-
0 notes -
Class: Array
- 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. For example, [e1, e2, e3].sum returns init + e1 + e2 + e3.
If a block is given, the block is applied to each element before addition.
If ary is empty, it returns init.
[].sum #=> 0 [].sum(0.0) #=> 0.0 [1, 2, 3].sum #=> 6 [3, 5.5].sum #=> 8.5 [2.5, 3.0].sum(0.0) {|e| e * e } #=> 15.25 [Object.new].sum #=> TypeError
The (arithmetic) mean value of an array can be obtained as follows.
mean = ary.sum(0.0) / ary.length
This method can be used for non-numeric objects by explicit init argument.
["a", "b", "c"].sum("") #=> "abc" [[1], [[2]], [3]].sum([]) #=> [1, [2], 3]
However, Array#join and Array#flatten is faster than Array#sum for array of strings and array of arrays.
["a", "b", "c"].join #=> "abc" [[1], [[2]], [3]].flatten(1) #=> [1, [2], 3]
Array#sum method may not respect method redefinition of “+” methods such as Integer#+.