Is there something method in ruby like python's reduce()?


#1

there is python’s build-in function reduce()'s definition

=====================================================================
reduce( function, sequence[, initializer])
Apply function of two arguments cumulatively to the items of
sequence, from left to right, so as to reduce the sequence to a single
value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and
the right argument, y, is the update value from the sequence. If the
optional initializer is present, it is placed before the items of the
sequence in the calculation, and serves as a default when the sequence
is empty. If initializer is not given and sequence contains only one
item, the first item is returned.

thanks.


#2

On 2/27/07, lnes removed_email_address@domain.invalid wrote:

optional initializer is present, it is placed before the items of the
sequence in the calculation, and serves as a default when the sequence
is empty. If initializer is not given and sequence contains only one
item, the first item is returned.

ri Enumerable#inject

thanks.


#3

it’s very useful, thanks!


#4

On 2/27/07, lnes removed_email_address@domain.invalid wrote:

there is python’s build-in function reduce()'s definition

There’s Enumerable#inject:

enum.inject(initial) {| memo, obj | block } => obj
enum.inject {| memo, obj | block } => obj

Combines the elements of enum by applying the block to an accumulator
value (memo) and each element in turn. At each step, memo is set to
the value returned by the block. The first form lets you supply an
initial value for memo. The second form uses the first element of the
collection as a the initial value (and skips that element while
iterating).

Sum some numbers

(5…10).inject {|sum, n| sum + n } #=> 45

Multiply some numbers

(5…10).inject(1) {|product, n| product * n } #=> 151200

find the longest word

longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=> “sheep”

find the length of the longest word

longest = %w{ cat sheep bear }.inject(0) do |memo,word|
memo >= word.length ? memo : word.length
end
longest #=> 5

It works for Arrays and any other classes that include the Enumerable
module.