Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
is there something method in ruby like python's reduce()?
lnes
2/28/2007 2:13:00 AM
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.
--
Posted via
http://www.ruby-...
.
2 Answers
Bira
2/28/2007 2:21:00 AM
0
On 2/27/07, lnes <huangliang2211@gmail.com> 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.
--
Bira
http://compexplicita.bl...
http://sinfoniaferida.bl...
lnes
2/28/2007 4:19:00 AM
0
it's very useful, thanks!
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
is there something method in ruby like python's reduce()?
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password