.jpg)
Example 1: Basic each loop with array
fruits = ["apple", "banana", "cherry"] fruits.each do |fruit| puts "I like #{fruit}s" end output : I like apples I like bananas I like cherrys
In this example, the program uses an each loop to iterate over an array of fruits and print a message for each one.
Example 2: each loop with hash
person = {name: "Alice", age: 30, occupation: "programmer"} person.each do |key, value| puts "#{key.capitalize}: #{value}" end Output: Name: Alice Age: 30 Occupation: programmer
In this example, the program uses an each loop to iterate over a hash and print each key-value pair with a capitalized key.
Example 3: each_with_index loop with array
fruits = ["apple", "banana", "cherry"] fruits.each_with_index do |fruit, index| puts "#{index+1}. #{fruit.capitalize}" end Output: 1. Apple 2. Banana 3. Cherry
In this example, the program uses an each_with_index loop to iterate over an array of fruits and print each one with its index.
Example 4: each loop with range
(1..5).each do |i|
puts "Value of i is #{i}"
end
Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5
In this example, the program uses an each loop to iterate over a range of numbers from 1 to 5 (inclusive) and print the current value of i.
Example 5: Chaining each loops with method chaining
numbers = [1, 2, 3, 4, 5] squares = numbers.map { |n| n * n } squares.each { |s| puts s } Output: 1 4 9 16 25
In this example, the program uses each loops to chain method calls together. The map method is used to create a new array of squared numbers, and the each method is used to iterate over that array and print each element.
0 Comments