[DOC] Tweaks for Array#sum

This commit is contained in:
BurdetteLamar 2024-10-17 17:31:28 -05:00 committed by Peter Zhu
parent 161ea389af
commit d1b5c10957
Notes: git 2024-10-18 15:13:12 +00:00

35
array.c
View File

@ -7924,40 +7924,41 @@ finish_exact_sum(long n, VALUE r, VALUE v, int z)
/* /*
* call-seq: * call-seq:
* array.sum(init = 0) -> object * sum(init = 0) -> object
* array.sum(init = 0) {|element| ... } -> object * sum(init = 0) {|element| ... } -> object
* *
* When no block is given, returns the object equivalent to: * With no block given, returns the sum of +init+ and all elements of +self+;
* for array +array+ and value +init+, equivalent to:
* *
* sum = init * sum = init
* array.each {|element| sum += element } * array.each {|element| sum += element }
* sum * sum
* *
* For example, <tt>[e1, e2, e3].sum</tt> returns <tt>init + e1 + e2 + e3</tt>. * For example, <tt>[e0, e1, e2].sum</tt> returns <tt>init + e0 + e1 + e2</tt>.
* *
* Examples: * Examples:
* *
* a = [0, 1, 2, 3] * [0, 1, 2, 3].sum # => 6
* a.sum # => 6 * [0, 1, 2, 3].sum(100) # => 106
* a.sum(100) # => 106 * ['abc', 'def', 'ghi'].sum('jkl') # => "jklabcdefghi"
* [[:foo, :bar], ['foo', 'bar']].sum([2, 3])
* # => [2, 3, :foo, :bar, "foo", "bar"]
* *
* The elements need not be numeric, but must be <tt>+</tt>-compatible * The +init+ value and elements need not be numeric, but must all be <tt>+</tt>-compatible:
* with each other and with +init+:
* *
* a = ['abc', 'def', 'ghi'] * # Raises TypeError: Array can't be coerced into Integer.
* a.sum('jkl') # => "jklabcdefghi" * [[:foo, :bar], ['foo', 'bar']].sum(2)
* *
* When a block is given, it is called with each element * With a block given, calls the block with each element of +self+;
* and the block's return value (instead of the element itself) is used as the addend: * the block's return value (instead of the element itself) is used as the addend:
* *
* a = ['zero', 1, :two] * ['zero', 1, :two].sum('Coerced and concatenated: ') {|element| element.to_s }
* s = a.sum('Coerced and concatenated: ') {|element| element.to_s } * # => "Coerced and concatenated: zero1two"
* s # => "Coerced and concatenated: zero1two"
* *
* Notes: * Notes:
* *
* - Array#join and Array#flatten may be faster than Array#sum * - Array#join and Array#flatten may be faster than Array#sum
* for an +Array+ of Strings or an +Array+ of Arrays. * for an array of strings or an array of arrays.
* - Array#sum method may not respect method redefinition of "+" methods such as Integer#+. * - Array#sum method may not respect method redefinition of "+" methods such as Integer#+.
* *
*/ */