Loops in Ruby Language

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
end

In 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}"
end

This 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!"
end

In 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}"
end

This 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
end

In this example, the code keeps running until count is greater than 5.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading