In Ruby, looping constructs are essential for executing a block of code multiple times. They provide the ability to iterate over collections, execute code until a condition is met, or repeat a set number of times. Here, we present three diverse examples of Ruby looping constructs:
each
Method for Iterating Over an ArrayThe each
method is commonly used to iterate over elements in an array. This is particularly useful for performing operations on each item without worrying about managing the index manually.
fruits = ['apple', 'banana', 'cherry']
fruits.each do |fruit|
puts "I love #{fruit}!"
end
This code snippet iterates over the fruits
array and prints a love statement for each fruit. It’s a straightforward way to process items in a collection.
fruit
in this case) can be named anything.while
Loop for Conditional RepetitionThe while
loop allows you to execute a block of code as long as a specified condition is true. This is useful when the number of iterations isn’t known beforehand.
count = 1
while count <= 5 do
puts "This is iteration number #{count}."
count += 1
end
In this example, the code prints the iteration number until the count exceeds 5. This demonstrates how to control the loop based on a condition.
break
to exit the loop prematurely if needed.times
Method for Fixed IterationThe times
method is perfect for executing a block of code a specific number of times. It’s particularly useful for scenarios where the exact number of iterations is predetermined.
5.times do |i|
puts "This is loop number #{i + 1}."
end
Here, the block runs 5 times, with i
representing the current iteration index, starting from 0. This is an efficient way to run a loop when the count is known ahead of time.
times
method returns the original integer used to call it.These examples of Ruby looping constructs offer practical insights into how loops can be effectively utilized in your Ruby programming endeavors.