Loops
7 min · Ruby
Repeat work without writing it out a hundred times.
Enemy 1 of 5
Ranges and .each
Rather than the C-style for (start; condition; step) loop you'll find in many languages, Ruby leans on ranges and iterator methods, which tend to read more like plain English. A range like 0..2 represents every value from 0 to 2, inclusive of both ends — so it covers exactly 0, 1, and 2. (A range written with three dots, 0...2, excludes the last value, covering just 0 and 1 — a subtle but important difference worth remembering.)
.each is a method every range (and array) has, and it's the idiomatic way to loop in Ruby: it hands you one value at a time through the block variable between the pipe characters (|i|), running the do ... end block once per value. This is a fundamentally different mental model from manually tracking an index and a stopping condition yourself — you're saying "for each value in this range, do this," and Ruby handles the mechanics of stepping through it.
do |i| ... end is called a block — a chunk of code you pass into a method, which the method then runs (often more than once). Blocks are one of Ruby's signature features, and you'll see the same pattern reused constantly, including with arrays' .map and .select later in this track.
Loading editor...