Types of Ruby Iterators
In Ruby, arrays and hashes are collections. Then there are iterators, which are methods that can be used on a collection. We will look at a few of these iterators in this post.
.each
The each method doesn’t modify the original collection and will always return the original collection.
pizza_toppings = [“cheese”, “pineapple”, “pepperoni”]pizza_toppings.each do |topping|
puts “I want #{topping} on my pizza.”
end
In the block of code above, we have a puts with a string and will print out each line with the topping.
I want cheese on my pizza.
I want pineapple on my pizza.
I want pepperoni on my pizza.
The return value is below.
=> [“cheese”, “pineapple”, “pepperoni”]
.map
The map method will return a modified version of the collection without modifying the original collection.
pizza_toppings = [“cheese”, “pineapple”, “pepperoni”]pizza_toppings.map do |topping|
“I want #{topping} on my pizza.”
end
The return value is below.
=> [“I want cheese on my pizza.”, “I want pineapple on my pizza.”, “I want pepperoni on my pizza.”]
Don’t forget that the original collection stays the same.
pizza_toppings
=> [“cheese”, “pineapple”, “pepperoni”]
.select
The select method is used to iterate through the collection and select the ones that evaluate to true.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]numbers.select do |number|
number.even?
end=> [2, 4, 6, 8, 10]