O'Reilly logo

Learning Ruby by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The while Loop

A while loop executes the code it contains as long as its conditional statement remains true. The following piece of code initializes a counter i to 0 and sets up an array containing four elements called breeds (horse breeds). It also creates a temporary array named temp. (You'll learn more about arrays in Chapter 6.)

The following few paragraphs are fairly fundamental, and are provided for beginning programmers. If you already have plenty of programming under your belt, skip ahead to the code itself.

The while loop will execute as long as its conditional (i < breeds.size) is true. The i variable starts out its little life equaling 0, and the size or length of the breeds array is 4.

As you come to the end of the loop, i is incremented by 1, and then control returns to the top of the loop. In the first loop, i equals 0, and is fed as 0 as an argument to breeds[i], which retrieves the first element (numbered 0). This is the string value quarter. That element is appended via << to the temp array. The capitalize method from String changes quarter to Quarter. At this point, 1 is added to i by the += operator, so i equals 1. And we take it again from the top.

This continues until i equals 4, whereupon the conditional test for while fails. The Ruby interpreter moves to the next valid statement, that is, temp.sort!, which sorts the new array alphabetically. It does not make a copy but changes the array in place. You know this by the tell-tale ! at the end of the method name ( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required