Loops and Iterators

Lesson 5 of 20

While loops, times, each and upto — make Ruby repeat the work without copy-pasting a single line.

The big picture

Repeat without repeating yourself

Loops run the same code many times with different data — Ruby gives you a low-level while and a family of elegant iterators.

while

Repeats as long as a condition stays true — check first, run after.

times

3.times { } runs a block exactly three times, counting from 0.

each

Walks a collection and hands you one element per pass.

upto

1.upto(5) counts up number by number.

break

Bail out of any loop the moment you are done.