Skip to content
Ruby

Iterators

Use each, map, select, reduce, group_by, and lazy enumerators.

By EZ4Code Team
iteratorenumerable

Code

# each - iterate without collecting
(1..5).each { |i| print i, " " }
puts

# map - transform to new array
squares = (1..5).map { |i| i * i }
puts squares.inspect

# select / reject - filter
evens = (1..10).select(&:even?)
odds  = (1..10).reject(&:even?)
puts evens.inspect
puts odds.inspect

# reduce - fold into single value
sum = (1..10).reduce(0) { |acc, n| acc + n }
puts sum

# inject with symbol shorthand
product = (1..5).inject(:*)
puts product

# each_with_index
%w[a b c].each_with_index { |c, i| puts "#{i}: #{c}" }

# group_by
words = %w[apple ant banana cherry apricot]
by_first = words.group_by { |w| w[0] }
puts by_first.inspect

# chunk_while for runs
runs = [1, 1, 2, 2, 3].chunk_while { |a, b| a == b }.to_a
puts runs.inspect

# Lazy infinite stream
primes = (2..).lazy.select { |n| (2...n).none? { |d| n % d == 0 } }
puts primes.first(5).inspect

Explanation

Ruby iterators are methods on Enumerable that yield each element to a block instead of using index counters. each iterates, map transforms, select filters, and reduce folds a sequence into a single value. Lazy enumerators defer computation so you can slice from infinite streams like the prime numbers.

More Ruby Snippets