each, map, and select (Ruby)

each iterates a collection running a block per element (returning the original); map transforms each element into a new array; select filters, keeping elements for which the block is true.

Ruby

These three are the workhorses of Ruby iteration. each is for side effects — it runs the block on every element and returns the original collection, so it's the idiomatic replacement for a for loop. map (alias collect) builds a brand-new array from each block result, used to transform data.

select (alias filter) keeps only the elements for which the block returns truthy, while its opposite reject drops them. find (alias detect) returns the first match. Because they return new collections (except each), they chain cleanly: list.select { ... }.map { ... }.

Prefer these over manual index loops: they're shorter, clearer about intent, and less error-prone. They come from the Enumerable module, so they work on arrays, hashes, ranges, and any custom enumerable.

Syntax

arr.each { |x| ... }
arr.map { |x| transform(x) }
arr.select { |x| condition(x) }

Examples

Ruby

nums = [1, 2, 3, 4]
puts nums.map { |n| n * n }.inspect
puts nums.select { |n| n.even? }.inspect
nums.each { |n| print n }

Output:

[1, 4, 9, 16]
[2, 4]
1234

Learn it in a lesson

See also

Back to the Dictionary