Basics

Ruby Loops

Loop Structures

Ruby loops use while and each with break and next.

Introduction to Ruby Loops

Loops in Ruby are used to execute a block of code repeatedly. Ruby provides several looping constructs, but in this guide, we'll focus on while loops and the each method. We'll also discuss how to control loop execution using break and next.

Using the while Loop

The while loop in Ruby repeats a block of code as long as a specified condition is true. It's useful when the number of iterations is not predetermined.

In this example, the loop will run as long as the variable i is less than 5. After each iteration, i is incremented by 1.

Iterating with the each Method

The each method is an iterator that goes through each element in a collection, such as an array or a hash. It is often used when you need to perform an action on each element of a collection.

This example prints each fruit in the array. The block of code inside do...end is executed for each element.

Controlling Loops with break

The break statement is used to exit a loop prematurely. It is useful when you want to stop the loop based on a certain condition.

In this example, even though the loop condition is true, the loop exits when i reaches 3 due to the break statement.

Using next to Skip Iterations

The next statement is used to skip the rest of the current iteration and move to the next one.

This example skips the iteration for even numbers, resulting in only odd numbers being printed.

Previous
Case