Throwin' Me For a Loop

August 7, 2014

Loops in Ruby are used to execute the same block of code a specified number of times, or until a condition is met.

The While Loop

The while loop executes code while a given condition evaluates to true. Be sure that your condition eventually evaluates to false, or you will create an infinite loop and crash your terminal. A while loop's conditional is separated from code by the word 'do', a newline, backslash, or semicolon.

The Until Loop

A complement to the while loop, the until loop executes code while a given condition evaluates to false. An until loop's conditional is separated from code by the word 'do', a newline, or semicolon.

The Times Loop

The times loop can be used on any variable containing a number or used on a number itself. You'll notice that the times loop uses the dot syntax (3.times do) rather than the keyword syntax used by the while and until loop. This has to do with how the times loop works under the hood, but it's used in the same way a while or until loop is used.

The For Loop/The Each Method

The most common loop in Ruby. The for loop executes code once for each element in the expression. A for loop's conditional is separated from code by the word 'do', a newline, or semicolon. Using a for loop, we can repeat a command as many times as we want. We can also vary its output depending on how many times it has run. However, in Ruby, the preferred way of doing a for loop is to use the each method (see below).

← Previous Post
Next Post →