Ruby Iterators
In Ruby, iterators are methods that allow you to traverse or iterate over a collection of elements. They provide a way to perform a set of operations on each element of a collection without needing to write repetitive code. Here’s a list of some common iterators in Ruby along with examples:
Get Vishal Pandey’s stories in your inbox
Join Medium for free to get updates from this writer.
each Iterator:
- Iterates over each element of a collection.
numbers = [1, 2, 3, 4, 5]
numbers.each { |n| puts n } # Output: 1 2 3 4 5map Iterator:
- Transforms each element of a collection and returns a new array with the transformed values.
numbers = [1, 2, 3, 4, 5]
doubled = numbers.map { |n| n * 2 }
puts doubled.inspect # Output: [2, 4, 6, 8, 10]select Iterator:
- Filters elements of a collection based on a condition and returns a new array with the selected elements.
numbers = [1, 2, 3, 4, 5]
evens = numbers.select { |n| n.even? }
puts evens.inspect # Output: [2, 4]reduce Iterator:
- Combines all elements of a collection into a single value by applying an accumulator function.
numbers = [1, 2, 3, 4, 5]
sum = numbers.reduce(0) { |acc, n| acc + n }
puts sum # Output: 15each_with_index Iterator:
- Iterates over each element of a collection along with its index.
fruits = ['apple', 'banana', 'cherry']
fruits.each_with_index { |fruit, index| puts "#{index}: #{fruit}" }
# Output:
# 0: apple
# 1: banana
# 2: cherrytimes Iterator:
- Executes a block a specified number of times.
3.times { |n| puts "Hello, #{n + 1}" }
# Output:
# Hello, 1
# Hello, 2
# Hello, 3upto and downto Iterators:
- Iterates from a starting value up to or down to an ending value.
1.upto(5) { |n| puts n } # Output: 1 2 3 4 5
5.downto(1) { |n| puts n } # Output: 5 4 3 2 1These are some of the most commonly used iterators in Ruby. They provide a concise and expressive way to work with collections of data.



