.jpg)
Example 1: Basic for loop
for i in 1..5 do
puts "Value of i is #{i}"
end
In this example, the program uses a for loop to iterate over a range of numbers from 1 to 5 (inclusive) and print the current value of i.
Example 2: for loop with array
fruits = ["apple", "banana", "cherry"]
for fruit in fruits do
puts "I like #{fruit}s"
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 a for loop to iterate over an array of fruits and print a message for each one.
Example 3: for loop with hash
person = {name: "Alice", age: 30, occupation: "programmer"}
for key, value in person do
puts "#{key.capitalize}: #{value}"
end
Output :
Name: Alice
Age: 30
Occupation: programmer
In this example, the program uses a for loop to iterate over a hash and print each key-value pair with a capitalized key.
Example 4: for loop with step
for i in 0.step(by: 2, to: 10) do
puts "Value of i is #{i}"
end
Output:
Value of i is 0
Value of i is 2
Value of i is 4
Value of i is 6
Value of i is 8
Value of i is 10
In this example, the program uses a for loop with the step method to iterate over a range of numbers from 0 to 10 (inclusive) in increments of 2.
Example 5: Nested for loops
for i in 1..3 do
for j in 1..3 do
puts "#{i} x #{j} = #{i*j}"
end
end
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
In this example, the program uses nested for loops to print the multiplication table from 1 to 3. The outer loop iterates over i and the inner loop iterates over j, so each combination of i and j is printed.

0 Comments