Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 134 ยท Collections

Iterating and Transforming Arrays

Learn Ruby array iteration and transformation - each, map, select, reject, reduce, each_with_object, partition, group_by, zip, flat_map, with step-by-step examples.

Most programs spend their time doing something to every element of a list: print it, convert it, filter it, add it up, group it. Ruby gives arrays a rich vocabulary for this, and learning it is the fastest way to write code that looks like Ruby instead of translated C. Instead of managing a counter and an accumulator yourself, you pick a method that names the intent: map to transform, select to filter, reduce to combine, group_by to bucket.

All the methods in this lesson take a block (see Blocks), and most of them come from the Enumerable module, which means they work on ranges, hashes and your own collections as well. You will learn what each one returns, how to chain them, how to choose between them, and the traps to avoid, such as changing an array while you walk through it.

each: do something with every element

each runs the block once per element and returns the array itself. Use it when you want a side effect, such as printing, and not a result.

Ruby each and each_with_index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that each returns the original array, which is rarely useful. each_with_index hands the block the element and its position. If you want the numbering to start at 1, use each.with_index(1). Ruby code seldom uses for loops or manual index counters; each and its relatives do the job (see Iterators and Blocks Basics).

map: transform every element

map (alias collect) returns a new array with the block's result for each element. The original is unchanged.

Ruby map builds a new array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

&:length is shorthand for { |word| word.length } (see Symbols). The block can use it for a single parameter (see Endless Methods and Modern Syntax). A common beginner mistake is using each with a manually built result array when map would do:

Ruby
# works, but noisy
result = []
prices.each { |price| result << price * 2 }

# idiomatic
result = prices.map { |price| price * 2 }

select, reject, find: filtering

select (alias filter) keeps the elements for which the block is truthy. reject keeps the others. find returns the first match, or nil.

Ruby Filtering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Careful with empty arrays: [].all? is true (nothing violates the rule) and [].any? is false. filter_map (Ruby 2.7) is a pleasant shortcut for select followed by map: it keeps the block's result when it is truthy and drops nil and false.

reduce: combine everything into one value

reduce (alias inject) carries an accumulator through the array. The block receives the accumulator and the next element, and its result becomes the new accumulator.

Ruby reduce step by step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

If you give reduce an initial value (0), that value starts the accumulator. Without one, the first element starts it, and the block runs from the second element on. Notice what happens on an empty array: reduce(:+) returns nil, while reduce(0, :+) and sum return 0. Prefer sum for adding numbers, because it is clearer and also handles floating-point rounding better: [0.1, 0.2, 0.3].sum is 0.6, while reduce(:+) gives 0.6000000000000001.

When the block always returns the same kind of container, use each_with_object instead of reduce. You then mutate the container and do not have to return it from every iteration, which avoids a very common bug.

each_with_object: build up a container

Ruby each_with_object versus reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Now the reduce bug itself. The block's last expression decides the next accumulator. If it is an assignment such as result[word] = word.length, the value is the number, not the hash:

Ruby Forgetting to return the accumulator (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

On the second round result is the Integer 5, so Ruby stops with undefined method '[]=' for an instance of Integer (NoMethodError). each_with_object ignores the block's return value, which removes that whole class of mistakes.

partition and group_by: splitting data

partition splits an array into two arrays (those for which the block is truthy, and the rest). group_by creates a hash from block result to elements. tally counts occurrences.

Ruby partition, group_by, tally, chunk_while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The two-element result of partition pairs well with multiple assignment (evens, odds = ...). slice_when and chunk_while cut a sequence between elements, which is perfect for finding runs of consecutive numbers.

zip, flat_map, each_slice, each_cons

Ruby Combining and slicing sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

zip pairs elements at the same position (missing values become nil). flat_map is map followed by flatten(1). each_slice(n) cuts the array into chunks of n, and each_cons(n) gives a sliding window: handy for moving averages or comparing neighbors.

Chaining

The real power appears when you chain methods. Read the chain from left to right, like a sentence.

Ruby A pipeline of small steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each step does one thing. If a chain gets long, give the intermediate results names. Be aware that every step builds a full intermediate array; for huge data or an early exit, use lazy (see Enumerators and Lazy Enumerators).

Mutating while iterating

Changing an array while each walks through it is a well-known source of bugs, because the iteration uses positions that move under its feet.

Ruby Deleting during each skips elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After the 2 is deleted, the 4 slides into position 0, but the iterator moves on to position 1, which now holds 6. The 4 is never looked at and survives, so the result is [4, 7] instead of [7]. The fix is to produce a new array with reject, or to use reject! or delete_if, which handle it safely.

Choosing the right method

You want to... Use
do something for each element each
transform each element map
keep or drop elements select, reject, filter_map
find one element find, find_index
answer yes/no all?, any?, none?, include?
collapse to one value sum, reduce, max, min
build a hash or other container each_with_object, to_h, group_by, tally
split in two partition
walk two lists together zip

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [1, 2, 3].each { |n| n * 2 } return?

    each returns the receiver itself. Use map when you want the block results.
  2. 2. What is the result of [1, 2, 3, 4].select(&:even?)?

    select keeps the elements for which the block is truthy, so only 2 and 4 remain.
  3. 3. Which call returns 0 for an empty array and the total for a non-empty array?

    sum starts from 0, so it returns 0 for an empty array. reduce without an initial value returns nil for an empty array.
  4. 4. Why is each_with_object({}) often safer than reduce({})?

    each_with_object ignores the block's return value, so forgetting to return the accumulator cannot break it.
  5. 5. What does %w[apple avocado banana].group_by { it[0] } return?

    group_by builds a hash from the block's result to the array of elements that produced it.

Summary

  • each is for side effects and returns the receiver; map returns a new array of block results.
  • select/filter, reject, find, filter_map and the predicates all?, any?, none?, one? filter and test.
  • sum adds numbers; reduce combines anything, and needs a starting value to be safe on empty arrays.
  • each_with_object builds containers without the return-the-accumulator trap.
  • partition, group_by, tally, zip, flat_map, each_slice and each_cons reshape data.
  • Chain small steps for readability; never delete from an array while iterating over it with each.

Next: Sorting and Searching Arrays