Home arrow Ruby-on-Rails arrow Exploring Iteration

Exploring Iteration

In this final part of a three-part series on code blocks and iteration, you'll learn how to stop an iteration, how to hide setup and clean up, and more. This article is excerpted from chapter eight of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 4
March 15, 2007
  1. · Exploring Iteration
  2. · 7.9 Looping Through Multiple Iterables in Parallel
  3. · 7.10 Hiding Setup and Cleanup in a Block Method
  4. · 7.11 Coupling Systems Loosely with Callbacks

print this article

Exploring Iteration
(Page 1 of 4 )

7.8 Stopping an Iteration


You want to interrupt an iteration from within the code block you passed into it.


The simplest way to interrupt execution is to use break. A breakstatement will jump out of the closest enclosing loop defined in the current method:

  1.upto(10) do |x|
puts x
break if x == 3
  # 1
  # 2
  # 3


The break statement is simple but it has several limitations. You can’t use breakwithin a code block defined withProc.newor (in Ruby 1.9 and up)Kernel#proc. If this is a problem for you, uselambdainstead:

  aBlock = Proc.new do |x|
puts x
break if x == 3
puts x +2

# 5
# 7

# 3
# LocalJumpError: break from proc-closure

More seriously, you can’t usebreakto jump out of multiple loops at once. Once a loop has run, there’s no way to know whether it completed normally or by usingbreak.

The simplest way around this problem is to enclose the code you want to skip within acatchblock with a descriptive symbolic name. You can thenthrowthe corresponding symbol when you want to jump to the end of thecatchblock. This lets you skip out of any number of nested loops and method calls.

Thethrow/catchsyntax isn’t exception handling—exceptions use araise/rescuesyntax. This is a special flow control construct designed to replace the use of exceptions for flow control (as sometimes happens in Java programs). It’s a bit like an old-style global GOTO, capable of suddenly moving execution to a faraway part of your program. It keeps your code more readable than a GOTO, though, because it’s restricted: athrowcan only jump to the end of a correspondingcatchblock.

The best example of thecatch..throwsyntax is theFind.findfunction described in Recipe 6.12. When you pass a code block intoFind.find, it yields up every directory and file in a certain directory tree. When your code block is given a directory, it can stopfindfrom recursing into that directory by callingFind.prune, which throws a:prunesymbol. Usingbreakwould stop thefindoperation altogether; throwing a symbol letsFind.pruneknow to just skip one directory.

Here’s a simplified view of theFind.findandFind.prunecode:

  def find(*paths)
    paths.each do |p|
      catch(:prune) do
        # Process p as a file or directory...
      # When you call Find.prune you'll end up here. 

  def prune
    throw :prune

When you callFind.prune, execution jumps to immediately after thecatch(:prune)block.Find.findthen starts processing the next file or directory.

See Also

  • Recipe 6.12, “Walking a Directory Tree”
  • ri Find

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials