Loops in Ruby Language
Loops are an essential part of any programming language, allowing developers to execute a block of code repeatedly. In Ruby, ther
e are several ways to create loops, each with its own unique characteristics. In this post, we’ll explore the most commonly used loop structures in Ruby with examples.while Loop
The while loop in Ruby executes a block of code as long as a given condition is true. Here’s an example:
count = 1
while count <= 5
puts "This is iteration #{count}"
count += 1
endIn this example, the code will keep running as long as count is less than or equal to 5.
for Loop
Ruby also supports the for loop, which is less commonly used compared to other loop types. It iterates through a range or collection of items. Here’s an example:
for i in 1..5
puts "This is iteration #{i}"
endThis code will print the message for values of i ranging from 1 to 5.
each Loop
The each loop is commonly used to iterate through collections like arrays and hashes. Here’s an example using an array:
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts "I love #{fruit}s!"
endIn this example, the code iterates through the fruits array and prints a message for each element.
times Loop
The times loop in Ruby is useful when you want to execute a block of code a specific number of times. Here’s an example:
5.times do |i|
puts "This is iteration #{i + 1}"
endThis code will execute the block of code five times, incrementing the value of i in each iteration.
until Loop
Similar to the while loop, the until loop executes a block of code until a specified condition becomes true. Here’s an example:
count = 1
until count > 5
puts "This is iteration #{count}"
count += 1
endIn this example, the code keeps running until count is greater than 5.
Discover more from PiEmbSysTech - Embedded Systems & VLSI Lab
Subscribe to get the latest posts sent to your email.


