What is the difference between collect,select, reject and
inject in ruby?
Some of the most
commonly used Enumerable iterators are
the rhyming methods collect , select , reject , and inject .
The
collect method (also known as map )
executes its associated block for each
element of the enumerable object, and collects the return values of the blocks
into an array:
squares = [1,2,3].collect {|x| x*x} # => [1,4,9]
The
select method invokes the associated
block for each element in the enumerable
object, and returns an array of elements for which the block
returns a value other than false or nil
. For example:
evens
= (1..10).select {|x| x%2 == 0} # => [2,4,6,8,10]
The
reject method is simply the opposite of
select ; it returns an array of elements for
which the block returns nil
or false . For example:
odds =
(1..10).reject {|x| x%2 == 0} # => [1,3,5,7,9]
The
inject method is a little more
complicated than the others. It invokes the associated
block with two arguments. The first argument is an
accumulated value of some sort from previous iterations. The second argument is
the next element of the enumerable object. The return value of the block
becomes the first block argument for the next iteration, or becomes the return
value of the iterator after the last iteration.
data = [2,
5, 3, 4]
sum =
data.inject {|sum, x| sum + x } # => 14 (2+5+3+4)
floatprod =
data.inject(1.0) {|p,x| p*x } # => 120.0 (1.0*2*5*3*4)
max =
data.inject {|m,x| m>x ? m : x } # => 5 (largest element)
No comments:
Post a Comment