0
0
Rubyprogramming~5 mins

Each for iteration in Ruby

Choose your learning style9 modes available
Introduction
You use 'each' to repeat a set of actions for every item in a list or collection. It helps you handle many items one by one easily.
When you want to print every name in a list of friends.
When you need to add a number to each item in a list of prices.
When you want to check each word in a sentence for a condition.
When you want to perform the same task on every element in an array.
Syntax
Ruby
collection.each do |item|
  # code to run for each item
end
The 'collection' can be an array, hash, or any list of items.
The 'item' inside the pipes | | is a temporary name for each element as you go through the list.
Examples
Prints each number in the array one by one.
Ruby
numbers = [1, 2, 3]
numbers.each do |num|
  puts num
end
Prints each fruit name in uppercase using a shorter block syntax.
Ruby
fruits = ['apple', 'banana', 'cherry']
fruits.each { |fruit| puts fruit.upcase }
Loops through a hash and prints each key with its value.
Ruby
hash = {a: 1, b: 2}
hash.each do |key, value|
  puts "#{key} is #{value}"
end
Sample Program
This program goes through each color in the list and prints a sentence saying you like that color.
Ruby
colors = ['red', 'green', 'blue']
colors.each do |color|
  puts "I like #{color}"
end
OutputSuccess
Important Notes
You can use 'each' with arrays, hashes, and other collections.
Inside the block, you can do anything with the current item, like change it or use it in calculations.
The 'each' method does not change the original collection unless you do it explicitly.
Summary
Use 'each' to repeat actions for every item in a list.
The block between 'do' and 'end' runs once per item.
It works with arrays, hashes, and other collections.