Sitemap
Vishal Pandey

Vishal Pandey

Senior Software Engineer@Thoughtworks

Ruby Iterators

2 min readApr 21, 2024

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 5

map 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: 15

each_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: cherry

times Iterator:

  • Executes a block a specified number of times.
3.times { |n| puts "Hello, #{n + 1}" }
# Output:
# Hello, 1
# Hello, 2
# Hello, 3

upto 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 1

These are some of the most commonly used iterators in Ruby. They provide a concise and expressive way to work with collections of data.

--

--

Vishal Pandey
Vishal Pandey

Written by Vishal Pandey

Senior Software Engineer@Thoughtworks