Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 5 / 68

Loops

In this lesson you will learn to repeat work with Ruby's each method, and get a feel for idiomatic Ruby looping. This is for anyone searching for "Ruby each how to use" or "Ruby loops".

Writing (range).each do |variable| ... end repeats work. The pairing of the each method with a block is a very important basic pattern that appears everywhere in Ruby code.

The sample code uses (1..5).each do |i| to take the numbers 1 through 5 one at a time and print a message. The part enclosed in do ... end is called a "block" - a chunk of work handed to the each method.

A common stumbling block for beginners is looking for a for statement like the one they know from other languages. Ruby does have for, but each with a block is the more common and more natural style, and that shift in thinking takes a moment.

The |i| part is the "block parameter", where each value taken from the range arrives. This each-plus-block pattern reappears in many methods you will meet later, such as map and select.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)