method

sum

Importance_2
v2_5_5 - Show latest stable - 0 notes - Class: Array
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#+.

Show source
Register or log in to add new notes.