Enumerable by task

Tasks and their methods

The Enumerable module is the same in arrays, hashes, ranges and files. One method per job, and the job is usually easy to name before the method is:

TaskMethod
Convert every itemmap { }
Keep the items that matchselect { }, reject { }
Split into two listspartition { }
Collapse to one valuereduce(:+), sum
Build a hash or a stringeach_with_object
Find the smallestmin_by { }, max_by { }
Ask a yes-or-no questionany? { }, all? { }
Count matchescount { }

Sum and reduce

sum adds numbers without a block, and with a block it adds the result of the block. That covers most of what reduce was used for:

ruby -e 'p (1..10).sum; p (1..10).select(&:even?).sum'

55
30

reduce is still the method for an operation that is not addition: a product, the longest string, a merge of hashes. partition returns both halves at once, which is cheaper than two select calls:

ruby -e 'p (1..10).partition(&:even?)'

[[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]

each_with_object

each_with_object passes a memo into the block, so a hash can be built without a variable outside the block. A hash with a default of zero counts in one line:

ruby -e 'p %w[a b a].each_with_object(Hash.new(0)) { |w, h| h[w] += 1 }'

{"a" => 2, "b" => 1}

The memo is the second block argument, which is the opposite of inject, where the accumulator comes first. The argument order is the usual reason the two get mixed; pick each_with_object when the result is a collection and reduce when it is a single value.

What to watch for

map returns an array even when the receiver is a hash: the result is pairs, not a hash. Use to_h after the map, or transform_values when only the values change.

A block with several statements loses the one-line charm and often hides a second job. When a block grows past three lines, name the step as a method and call it from the block.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which method keeps only the items that match a block?

    Answer

    select

    select keeps the matching items, and reject keeps the others.

  2. Which method splits a collection into two lists in one pass?

    Answer

    partition

    partition returns the matching and the rest together, cheaper than two select calls.

  3. What does this program print? p (1..10).select(&:even?).sum

    Answer

    30

    The even numbers 2, 4, 6, 8 and 10 add up to 30.

  4. What does (1..10).sum return?

    Answer

    55

    sum adds every number of the range, and the total is 55.

  5. What does this program print? p (1..10).partition(&:even?)

    Answer

    [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]

    The first list holds the items whose block result is true.

  6. Where is the memo in the block of each_with_object?

    Answer

    The second argument

    each_with_object passes the element first and the memo second, opposite to inject.

  7. What does this program print? p %w[a b a].each_with_object(Hash.new(0)) { |w, h| h[w] += 1 }

    Answer

    {"a" => 2, "b" => 1}

    The memo hash counts each word, and a appears twice.

  8. What does map return when the receiver is a hash?

    Answer

    An array of pairs

    The block result for each pair becomes an array element, so to_h is needed to get a hash back.

  9. Which call turns an array of pairs into a hash?

    Answer

    to_h

    to_h reads each two-element array as a key and a value.

  10. Which method counts the items that match a block?

    Answer

    count { }

    count with a block counts the items whose block result is true.

Article author: Arthur Isaev