Iterators & Enumerators in Ruby
Use Ruby's powerful iterators like map, select, reject, reduce, each_with_object, and lazy enumerators.
Ruby's Iteration Model
In Ruby, iteration is built on blocks. Methods like each, map, and select accept a block and call it for each element. This is more expressive than manual for loops.
1. each — Basic Iteration
Iterate over any collection.
2. each_with_index
Access index alongside element.
3. times, upto, downto
Numeric iteration shortcuts.
Transforming Collections
map (also called collect) transforms each element. flat_map maps and flattens. zip combines arrays element-by-element.
1. map / collect
Transform each element.
2. flat_map
Map and flatten one level.
3. zip
Combine multiple arrays element-by-element.
Filtering Collections
select (alias filter) keeps elements matching a condition. reject keeps those that do NOT match. find returns the first match.
1. select / filter
Keep elements matching condition.
2. reject
Exclude elements matching condition.
3. find / detect
Return first matching element.
Reducing & Aggregating
reduce (also inject) folds a collection into a single value. Ruby also provides convenient built-ins like sum, min, max, count.
1. reduce / inject
Fold collection into single value.
2. reduce with Symbol Shorthand
Pass operator as symbol.
3. Built-in Aggregation Methods
sum, min, max, count.
Grouping & Sorting
Ruby provides high-level grouping and sorting methods that work with any Enumerable.
1. group_by
Group elements by a computed key.
2. sort_by
Sort by a computed key.
3. each_slice and each_cons
Process elements in batches or windows.
4. tally
Count occurrences of each element.
Enumerator & Lazy Evaluation
Ruby's Enumerator class lets you create custom iterators. Calling .lazy on any Enumerable gives a lazy chain that processes elements on demand — ideal for large or infinite sequences.
1. Custom Enumerator with Enumerator.new
Build a custom iterator.
2. Lazy Enumerator
Process only what you need.
3. each_with_object
Build an object while iterating.