We use each to go through every item in a list one by one. It helps us do something with each item easily.
Each as the primary iterator in Ruby
collection.each do |item| # code to run for each item end
The each method works on collections like arrays and hashes.
The block between do and end runs once for each item.
numbers = [1, 2, 3] numbers.each do |number| puts number end
empty_array = [] empty_array.each do |item| puts item end
single_item = [42] single_item.each do |item| puts item end
hash = {a: 1, b: 2}
hash.each do |key, value|
puts "Key: #{key}, Value: #{value}"
endThis program shows how each goes through the list of fruits and prints a message for each one. The original list stays the same.
fruits = ["apple", "banana", "cherry"] puts "Fruits before iteration:" puts fruits fruits.each do |fruit| puts "I like #{fruit}!" end puts "Fruits after iteration:" puts fruits
Time complexity: each runs once for every item, so it is O(n) where n is the number of items.
Space complexity: each does not create a new list, so it uses little extra space.
A common mistake is trying to change the original list inside each without reassigning it, which does not work.
Use each when you want to do something with each item but do not need to create a new list. Use map if you want a new list with changed items.
each helps you do something with every item in a list.
It works on arrays and hashes by running a block of code for each item.
The original list stays the same after using each.