May 012011
 

Ruby’s most commonly used method is probably each, an iterator that can act on an Array, Hash, Range, or any other array-like object. (It can also act on non-array like objects such as IO, in which case .each will iterate over each line).

There are four iterators built on top of each, called the Enumerable iterators. You can use them on any enumerable objects.

Method What it does
collect / map Collect works just like each except for the returned value: it returns an array constructed as the result of calling the block for each item in the array.

Map is a synonym of collect.

select Select invokes the block for each element and returns an array of the original elements for which the block returns true.
reject Reject invokes the block for each element and returns an array of the original elements for which the block returns false.
inject Inject is a special case that takes a block with two arguments: a value to accumulate and the value in the list. This is complicated enough for its own blog post.

Notice the specific difference between each and collect. Each will evaluate the block but throws away the result of each block’s evaluation and returns the original array, whereas collect uses the result of each block’s execute to create a new array comprised of these results.

Consider the following example:

irb(main):> [1,2,3].each{|x| x*2}
=> [1, 2, 3]
irb(main):> [1,2,3].collect{|x| x*2}
=> [2, 4, 6]

Notice how the returned value of each is the original array, whereas the returned value of collect is a new array with each value multiplied by two.

Select example:
Select only numbers that are even. Note that [1..10] creates an array like [1,2,3,4,5,6,7,8,9,10]

irb(main):> [1..10].select{|x| x%2 == 0}
=> [2, 4, 6, 8, 10]

Reject example:
Reject numbers that are multiples of 3

irb(main):> [1..10].reject{|x| x%3 == 0 }
=> [1, 2, 4, 5, 7, 8, 10]
 Posted by at 12:00 am  Tagged with: