Revisiting Ruby Loops and Iterations

Topic Overview

Hello, Explorer! In this lesson, we will revisit Ruby loops, essential tools that simplify repetitive tasks.

Think of loops as a playlist on repeat. We will explore the Ruby looping universe and gain hands-on experience by applying loops to collections like arrays and strings.

Understanding Looping

Have you ever listened to your favorite song on repeat? That's what loops are about in programming: repeating a sequence of steps efficiently. Let’s take a look at how you can greet a list of friends using an each loop:

friends = ['Alice', 'Bob', 'Charlie', 'Daniel']
friends.each do |friend|
  puts "Hello, #{friend}! Nice to meet you."
end
# Output:
# Hello, Alice! Nice to meet you.
# Hello, Bob! Nice to meet you.
# Hello, Charlie! Nice to meet you.
# Hello, Daniel! Nice to meet you.

Here, the loop iterates through the friends array, printing a personalized greeting for each name.

For Loop and Alternatives in Ruby

Ruby provides a for loop to iterate over any enumerable collection. While Rubyists often prefer methods like .each or .times for better readability, the for loop is straightforward and useful in certain cases.

Let's explore both of these options with 2 quick examples.

Example: Simple `for` Loop

Here’s how you can print a range of numbers using a for loop:

for num in 0..4
  puts num
end
# Output:
# 0
# 1
# 2
# 3
# 4

In this example, the for loop iterates over the range 0..4, assigning each value to num on each iteration and printing it.

Example: .times Loop

Alternatively, you can achieve the same result using a .times loop:

5.times do |num|
  puts num
end
# Output:
# 0
# 1
# 2
# 3
# 4

Here, the loop runs 5 times, printing numbers from 0 to 4. The .times method is concise and works well when the iteration count is fixed.

While Loop in Ruby

The while loop executes code continuously until a condition becomes false. Here’s a simple example:

num = 0
while num < 5
  puts num
  num += 1
end
# Output:
# 0
# 1
# 2
# 3
# 4

Before each iteration, Ruby checks the condition (num < 5). If it's true, the code block runs; otherwise, the loop exits.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal