Nested arrays and hashes
Rows of hashes
Most APIs answer with a list of objects, and Ruby reads that as an array of hashes. One row per record, one key per column, and the work is almost always grouping or sorting:
rows = [ { n: "a", v: 2 }, { n: "b", v: 1 }, { n: "c", v: 2 } ] puts rows.length
ruby rows.rb
3
The block variable is a hash, so row[:n] reads a column and row[:v] reads the one to group by. _1 stands for the first block argument, which keeps the one-liners short.
group_by
group_by returns a hash of lists keyed by the block result, and transform_values turns each list into the values the report needs:
ruby -e 'rows = [{n: "a", v: 2}, {n: "b", v: 1}, {n: "c", v: 2}]; p rows.group_by { _1[:v] }.transform_values { |r| r.map { _1[:n] } }'
{2 => ["a", "c"], 1 => ["b"]}
The keys keep the order of first appearance, not a sorted order. Sort the result when a report should be stable: sort_by { |k, _| k } is enough for numeric keys.
Sorting by a key
sort_by with one key is the readable form; a second key in the block decides ties:
ruby -e 'rows = [{n: "a", v: 2}, {n: "b", v: 1}]; p rows.sort_by { _1[:v] }.map { _1[:n] }'
["b", "a"]
For more than one key, return an array from the block: sort_by { |row| [row[:v], row[:n]] }. Ruby 3.x sorts arrays element by element, so the first key decides and the second breaks the tie, which is what a report header implies.
What to watch for
A missing key in a row gives nil, and the error
appears at the first method call on that nil, far from the row. Validate
the columns once, before the loop
(rows.each { |row| row.fetch(:n) }), or use
dig when a column is optional.
Deeply nested rows are the usual place where a small class is better than
a hash. When three levels of [:a][:b][:c] appear
in a method, a Struct or a class with named
readers says the same thing and fails earlier.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How is a list of records from an API usually read in Ruby?
Answer
As an array of hashes, one row per record
One hash per row, with one key per column, is the shape the lesson works with.
-
What does this program print?
rows = [{n: "a", v: 2}, {n: "b", v: 1}, {n: "c", v: 2}] p rows.group_by { _1[:v] }.transform_values { |r| r.map { _1[:n] } }Answer
{2 => ["a", "c"], 1 => ["b"]}
group_by keeps the first appearance order, so the key 2 comes before 1.
-
What does
group_byreturn?Answer
A hash whose keys are the block results and whose values are lists
Each group is the list of rows that produced the same key.
-
In which order do the keys of a group_by hash appear?
Answer
First appearance
The lesson says to sort the result when a report needs a stable order.
-
What does this program print?
rows = [{n: "a", v: 2}, {n: "b", v: 1}] p rows.sort_by { _1[:v] }.map { _1[:n] }Answer
["b", "a"]
The row with v = 1 comes first, so b is before a.
-
How do you sort by two keys with
sort_by?Answer
Return an array of the keys from the block
Ruby sorts arrays element by element, so [v, n] breaks ties by n.
-
What does this program print?
rows = [{n: "a", v: 2}, {n: "b", v: 1}] p rows.sort_by { |row| [row[:v], row[:n]] }.map { _1[:n] }Answer
["b", "a"]
The v key decides first; there is no tie here, so n never breaks one.
-
What does
row[:n]return when the row has no :n key?Answer
nil
The brackets are quiet, and the error comes later when a method is called on the nil.
-
How does the lesson suggest validating the columns once?
Answer
(rows.each { |row| row.fetch(:n) })
fetch raises at the bad row, where the problem is, instead of three methods later.
-
When is a Struct or a class better than three levels of hash?
Answer
When the nesting is deep and named readers would fail earlier
A named reader says what the column is and raises on a missing field.
Article author: Arthur Isaev