RUBY / CHAPTER 06

Enumerable transformations

Intermediate

Choose collection operations from the desired result shape.

By the end of this chapter

  • Distinguish map, select, and reduce
  • Use group_by for a partitioned result
  • Keep a transformation pipeline readable

The idea

Enumerable provides operations for objects that support each. Map transforms entries, select keeps entries satisfying a predicate, and reduce combines them with an accumulator. Choose an operation by describing the result shape first. Supplying an initial accumulator makes reduce behavior on empty input explicit. An ordinary loop may be clearer than a long chain when several outputs or error paths are involved.

Group_by partitions elements into a hash of arrays using the block’s result as the key. Elements remain in encounter order within each group. Keep transformations separate from side effects when possible so intermediate results can be inspected. Methods that construct a new outer collection can still share contained objects, so avoid assuming that map or select creates deeply independent records.

Ruby example
rows = [{team: "A", points: 2}, {team: "B", points: 4}, {team: "A", points: 3}]
totals = rows.group_by { |row| row[:team] }.transform_values { |group| group.sum { |row| row[:points] } }
p totals
Result
{"A"=>5, "B"=>4}

Grouping creates two arrays, and each group’s points are summed. The resulting hash uses team names as keys and numeric totals as values.

Try it yourself

Return the IDs of active records, preserving input order and leaving the records unchanged.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which method returns only elements for which a block is truthy?