The each iterator is a fundamental concept in Ruby, essential for working with collections. It provides a simple and efficient way to iterate over arrays, hashes, and other enumerable objects.
The each method allows you to perform an operation on every element of a collection. It's a cornerstone of Ruby's enumerable module, offering a clean and readable approach to iteration.
collection.each do |item|
# Code to be executed for each item
end
Here, collection is the object you're iterating over, and item represents each element during iteration.
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts "I love #{fruit}!"
end
This code will print:
I love apple!
I love banana!
I love cherry!
person = { name: "Alice", age: 30, city: "New York" }
person.each do |key, value|
puts "#{key}: #{value}"
end
Output:
name: Alice
age: 30
city: New York
each iterator doesn't modify the original collection.each with any object that includes the Enumerable module.collection.each { |item| # code }While each is versatile, Ruby offers other iterators for specific use cases:
each when you need to perform an action on each element without transforming the collection.map or select when appropriate.The each iterator is a powerful tool in Ruby programming. It simplifies collection traversal and is often the go-to choice for many iteration tasks. By mastering each, you'll significantly enhance your ability to write clean, efficient Ruby code.
To deepen your understanding of Ruby iteration, explore these related topics: