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:
| Task | Method |
|---|---|
| Convert every item | map { } |
| Keep the items that match | select { }, reject { } |
| Split into two lists | partition { } |
| Collapse to one value | reduce(:+), sum |
| Build a hash or a string | each_with_object |
| Find the smallest | min_by { }, max_by { } |
| Ask a yes-or-no question | any? { }, all? { } |
| Count matches | count { } |
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.
-
Which method keeps only the items that match a block?
Answer
select
select keeps the matching items, and reject keeps the others.
-
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.
-
What does this program print?
p (1..10).select(&:even?).sumAnswer
30
The even numbers 2, 4, 6, 8 and 10 add up to 30.
-
What does
(1..10).sumreturn?Answer
55
sum adds every number of the range, and the total is 55.
-
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.
-
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.
-
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.
-
What does
mapreturn 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.
-
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.
-
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