The for loop in Ruby is used to iterate over a collection such as a range, an array, or a hash. Although Rubyists often prefer using iterators like each, the for loop can still be quite useful.
Syntax
for variable in collection
# code to execute
end
Example 1: Iterating Over a Range
for i in 1..5
puts i
end
Explanation: This will print the numbers 1 through 5, one per line. 1..5
is a range, and the for loop iterates over each number in this range.
Example 2: Iterating Over an Array
fruits = ["apple", "banana", "cherry"]
for fruit in fruits
puts fruit
end
Explanation: This will print each fruit in the array (apple
, banana
, cherry
) on a new line. The for
loop iterates over each element in the fruits
array.
Example 3: Iterating Over a Hash
hash = {a: 1, b: 2, c: 3}
for key, value in hash
puts "#{key} => #{value}"
end
Explanation: This will print each key-value pair in the hash (a => 1
, b => 2
, c => 3
). The for loop iterates over each key-value pair in the hash
.