Iterators in Ruby Language

Iterators in Ruby Language

Ruby is a versatile and expressive programming language that encourages developers to write clean and concise c

ode. One of the language’s key features that facilitates this is its robust support for iterators. Iterators allow you to loop through collections like arrays, hashes, and other data structures in a convenient and elegant way. In this post, we will explore iterators in Ruby with examples to demonstrate their power and flexibility.

What are Iterators in Ruby?

Iterators are methods or constructs that enable you to traverse elements of a collection, such as an array or a hash, one at a time. They eliminate the need for manually managing loop counters and provide a more readable and concise way to work with collections.

Ruby offers a rich set of built-in iterators, making it easy to perform repetitive operations on data structures. Let’s take a look at some of the most commonly used iterators in Ruby:

  • each

The each iterator is used to iterate over elements in an array or a hash. It yields each element to a block of code, allowing you to perform actions on each item in the collection. Here’s an example:

numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
  puts number
end

This code will print each number from the numbers array.

  • times

The times iterator is used to execute a block of code a specified number of times. It’s often used for simple counting and repetitive tasks:

5.times do |i|
  puts "Iteration #{i + 1}"
end

This code will print the message “Iteration 1” through “Iteration 5.”

  • map

The map iterator is used to transform elements in an array and create a new array with the results. It’s an elegant way to perform operations on each item without modifying the original array:

numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map { |number| number * number }
puts squared_numbers

This code will output [1, 4, 9, 16, 25].

  • each_with_index

The each_with_index iterator is handy when you need to access both the element and its index during iteration:

fruits = ["apple", "banana", "cherry"]
fruits.each_with_index do |fruit, index|
  puts "#{index + 1}. #{fruit}"
end

This code will number and print each fruit in the array.

Custom Iterators

Ruby also allows you to create custom iterators using the yield keyword. This enables you to build specialized iteration logic tailored to your specific needs.

def custom_iterator
  yield("first value")
  yield("second value")
  yield("third value")
end

custom_iterator do |value|
  puts "Received: #{value}"
end

This code defines a custom iterator that yields three values, and the block provided to the iterator prints each value.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading