Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What are Iterators in Ruby?

In the world of programming, iterating over a collection of data is a common task. Imagine you have a list of names, and you need to print each name on the screen, or you have a list of numbers and you need to calculate the sum of those numbers. In both cases, you need to go through each item and perform a specific operation. In this blog post, we will discuss iterators in Ruby, which help us perform such tasks with ease.

What are Iterators?

Iterators are methods that allow you to traverse a collection of data, like an array or a hash, and perform some operation on each element in the collection. Ruby has built-in iterators that make it simple and efficient to work with collections. Some examples of iterators are each, map, and select.

Before we dive into examples and explanations, let's understand some terms that will help you grasp the concept of iterators:

  • Collection: A collection is a set of data, like an array or a hash. For example, an array of names or a hash of key-value pairs.
  • Element: An element is an individual item within a collection. For example, in an array of names, each name is an element of that array.
  • Block: A block is a piece of code enclosed in curly braces {} or do..end that is passed to an iterator. The iterator executes this block of code for each element in the collection.

Now that we have a basic understanding of these terms, let's dive into some examples of iterators and how they work.

each Iterator

The each iterator is perhaps the most commonly used iterator in Ruby. It allows you to perform a specific operation on each element of a collection. The each iterator can be used with both arrays and hashes.

Let's consider an example with an array of names:

names = ["Alice", "Bob", "Charlie", "Dave"]

names.each do |name|
  puts name
end

In this example, we have an array called names containing four names. We use the each iterator to print each name on the screen. The each iterator is called on the names array and we pass a block of code to it. The block of code uses the puts method to print the name. The variable name inside the block is a temporary variable that represents the current element of the array as the each iterator goes through it.

Here's the same example using curly braces instead of do..end:

names = ["Alice", "Bob", "Charlie", "Dave"]

names.each { |name| puts name }

The each iterator can also be used with hashes. Here's an example:

ages = { "Alice" => 30, "Bob" => 25, "Charlie" => 22, "Dave" => 28 }

ages.each do |name, age|
  puts "#{name} is #{age} years old."
end

In this example, we have a hash called ages containing names as keys and ages as values. We use the each iterator to print a sentence about each person's age. The each iterator is called on the ages hash, and we pass a block of code to it. The block of code uses the puts method to print the sentence. The variables name and age inside the block are temporary variables that represent the current key-value pair of the hash as the each iterator goes through it.

map Iterator

The map iterator is another useful iterator in Ruby. It allows you to create a new array by applying a specific operation to each element of an existing array. Unlike the each iterator, which does not return a value, the map iterator returns a new array containing the results of the operation.

Here's an example of using the map iterator to square each number in an array:

numbers = [1, 2, 3, 4, 5]

squares = numbers.map do |number|
  number * number
end

puts squares.inspect

In this example, we have an array called numbers containing five numbers. We use the map iterator to create a new array called squares that contains the squares of the numbers in the numbers array. The map iterator is called on the numbers array, and we pass a block of code to it. The block of code calculates the square of the current number. The variable number inside the block is a temporary variable that represents the current element of the array as the map iterator goes through it.

The output of this example would be:

[1, 4, 9, 16, 25]

Here's the same example using curly braces instead of do..end:

numbers = [1, 2, 3, 4, 5]

squares = numbers.map { |number| number * number }

puts squares.inspect

select Iterator

The select iterator allows you to create a new array containing only the elements that satisfy a specific condition. Like the map iterator, the select iterator also returns a new array.

Here's an example of using the select iterator to find even numbers from an array:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = numbers.select do |number|
  number % 2 == 0
end

puts even_numbers.inspect

In this example, we have an array called numbers containing ten numbers. We use the select iterator to create a new array called even_numbers that contains only the even numbers from the numbers array. The select iterator is called on the numbers array, and we pass a block of code to it. The block of code checks if the current number is even. The variable number inside the block is a temporary variable that represents the current element of the array as the select iterator goes through it.

The output of this example would be:

[2, 4, 6, 8, 10]

Here's the same example using curly braces instead of do..end:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = numbers.select { |number| number % 2 == 0 }

puts even_numbers.inspect

Conclusion

Iterators in Ruby make it easy and efficient to work with collections of data. In this blog post, we discussed what iterators are and how they work, along with some examples of the most commonly used iterators, such as each, map, and select. These iterators, along with other built-in iterators, provide a powerful way to manipulate and process data in Ruby.

As you continue your journey in learning Ruby, you will come across many more iterators and their applications. We hope that this blog post has given you a solid foundation to understand iterators in Ruby and apply them in your own projects. Happy coding!