liveBook · Manning

Loop

As explained in The Well-Grounded Rubyist, Fourth Edition

A loop is a control-flow construct that repeatedly executes a segment of code according to an unconditional, conditional, or collection-based rule.

A loop repeats a segment of code. Ruby can repeat it indefinitely, while or until a condition changes, or once for each value in a collection. The choice determines both when the body runs and how repetition stops. section 6.2 section 6.2.3

Stop or skip an iteration

The loop method takes a code block and repeats it. For example, n = 1; loop do; n += 1; break if n > 9; end stops when n reaches 10. Use next instead of break to skip the rest of the current iteration and start another. section 6.2.1

Use while when the body should repeat while its condition is true; use until when it should repeat until its condition becomes true. A condition placed before the body can prevent any execution. With begin/end and the condition after the body, the body runs once before the first test. section 6.2.2

Listing 6.3 Using for/in with the Temperature class
class Temperature
  def Temperature.c2f(celsius)
    celsius * 9.0 / 5 + 32
  end
end
celsius = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
puts "Celsius\tFahrenheit" #1
for c in celsius
  puts "#{c}\t#{Temperature.c2f(c)}"
end

The for/in loop assigns each Celsius value from the array to c, then prints its Fahrenheit equivalent. Its body runs once per array value. section 6.2.3

The loop method is also an iterator: it repeatedly runs the block supplied with its call. An iterator can do this with yield. When the block finishes, control returns to the still-running method, which can yield again. A block belongs to the method-call syntax; it is not a normal argument. section 6.3.1 section 6.3.2

def my_loop
  while true
    yield
  end
end

This small loop-like method uses while true to keep reaching yield, showing how repeated block execution can be built from conditional looping. section 6.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through break, next, conditional test placement, and a loop reimplementation using yield.
Examples
Uses a counter, integer printing, Celsius-to-Fahrenheit conversion, and a loop-like method.
What it assumes
Assumes familiarity with method calls and variables while introducing blocks provisionally before explaining yield.
What you can do after
Build it from scratch with a method that repeatedly yields, and choose a Ruby loop form for a repetition task.
How it connects
Connects loops to conditionals, arrays, iterators, code blocks, and yield.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.