Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Exploring Iteration
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Exploring Iteration
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2007-03-15

    Table of Contents:
  • Exploring Iteration
  • 7.9 Looping Through Multiple Iterables in Parallel
  • 7.10 Hiding Setup and Cleanup in a Block Method
  • 7.11 Coupling Systems Loosely with Callbacks

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Iron Speed
     
    ADVERTISEMENT

    At the virtual BlackBerry Technical Seminar 2008, you can ask your development questions directly of Research In Motion® (RIM) experts, and take advantage of learning opportunities designed uniquely for BlackBerry solution developers. Register Today!

    Exploring Iteration


    (Page 1 of 4 )

    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.

    7.8 Stopping an Iteration

    Problem

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

    Solution

    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
     
    end
      # 1
      # 2
      # 3

    Discussion

    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
      end

      aBlock.call(5)
     
    # 5
     
    # 7

      aBlock.call(3)
     
    # 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...
          end
          # When you call Find.prune you'll end up here. 
        
    end
      end

      def prune
        throw :prune
      end

    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

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Ruby Cookbook," published by O'Reilly. We...
     

    Buy this book now. This article is excerpted from chapter eight of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops
    - Ruby Conditionals
    - Ruby Operators and Arrays
    - Ruby for the Newbie


    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway