Fork me on GitHub

Project Notes

Ruby Loops

All the various ways of looping in Ruby.


The basic for <variable> in <enumerable> <block> structure is common, especially when iterating aribitrary ranges.

See ruby doc: for loop


When needing to iterate all items in a collection, the <enumerable>.each <block> structure is generally preferred.

See ruby doc: Array#each


The while <condition> <block> structure is ideal for when the condition needs to be checked before any iteration.

See ruby doc: while loop


The until <condition> <block> structure is similar to while except uses the complimentay condition. The condition is checked before the block is executed.

See ruby doc: until 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>

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


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

Credits and References

About LCK#134 ruby
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.