#129 Loops
All the various ways of looping in Ruby.
Notes
for..in
The basic for <variable> in <enumerable> <block>
structure is common, especially when iterating aribitrary ranges.
each
When needing to iterate all items in a collection, the <enumerable>.each <block>
structure is generally preferred.
while
The while <condition> <block>
structure is ideal for when the condition needs to be checked before any iteration.
Until
The until <condition> <block>
structure is similar to while
except uses the complimentay condition.
The condition is checked before the block is executed.
Loop
The loop
syntax is a shortcut for an infinite while true <block>
loop. A break
condition would be used to exit the loop.
See ruby doc: break
loop do
...
break if <cond>
end
Unless/While Modifiers
An old, now discouraged (Re: semenatics of if/unless/while statement modifiers) syntax is to apply a while/until modifier to a block.
ruby doc: while/until modifiers
Why discouraged? .. because it’s hard for users to tell
begin end while
works differently from
while
Running the Examples
See examples.rb; these demonstrations are written asa test suite:
$ ruby examples.rb
Run options: --seed 8730
# Running:
...........
Finished in 0.001201s, 9159.0354 runs/s, 9159.0354 assertions/s.
11 runs, 11 assertions, 0 failures, 0 errors, 0 skips