AnyCompiler

Enumerable Methods

The Enumerable module (mixed into Array, Hash, Range, and more — the same mixin mechanism lesson 16 covers for your own classes) is where .map, .select, and .reduce live. Each takes a block: .select keeps elements the block returns a truthy value for, .map transforms every element through the block, and .reduce (aliased .inject) folds the whole collection down to one accumulated value.

nums = [1, 2, 3, 4, 5, 6]
evens = nums.select { |n| n.even? }
doubled = evens.map { |n| n * 2 }
total = doubled.reduce(0) { |sum, n| sum + n }

puts evens.inspect
puts doubled.inspect
puts total
Output
[2, 4, 6]
[4, 8, 12]
24

Because every one of these methods returns a new collection (or a value), idiomatic Ruby usually chains them directly in one expression instead of naming each intermediate step:

nums = [1, 2, 3, 4, 5, 6]
puts nums.map { |n| n * n }.select { |n| n > 10 }.inspect
Output
[16, 25, 36]

Square every number, then keep only the results over 10 — read left to right as a pipeline. This chaining style, leaning on blocks at every step, is what idiomatic Ruby collection code looks like in practice. Next: classes and objects — class, initialize, and instance variables.

Practice exercise

Given nums = [1, 2, 3, 4, 5, 6], select the even numbers, square each with map, then sum them with reduce. Print the total.