Languages

Fsharp
ActionScript
xBase
Clean
GPSS
PureBasic
Sieve
Erlang
JOVIAL
Mercury
Linda
DataFlex
PostScript
FoxPro2
VFP
Cobol
Prolog
Jython
Awk
VisualBasic
JavaScript
Matlab
ASP
Haskell
Csharp
D
Smalltalk
Nemerle
Pixilang
Java
SQL
Python
ObjectPascal
Ruby
Perl
Pascal
Assembler
PHP
C
Functions  Add function  Users  Registration  Enter   About  ASCII Table  Our helpers

Ruby-on-Rails


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

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
1 2 3 4
Latest "Green" Packing Material? Mushrooms!

EcoCradle packaging material is composed of agricultural byproducts bound by fungal roots.

A new packing material that grows itself is now appearing in shipped products across the country.

The composite of inedible agricultural waste and mushroom roots is called Mycobond™, and its manufacture requires just one eighth the energy and one tenth the carbon dioxide of traditional foam packing material.

And unlike most foam substitutes, when no longer useful, it makes great compost in the garden.

The technology was the brainchild of two former Rensselaer ...

More at http://www.nsf.gov/news/news_summ.jsp?cntn_id=117385&WT.mc_id=USNSF_51&WT.mc_ev=click


This is an NSF News item.

PycckaR
BepcuR


Articles
Articles


Library
Library


Downloads
Downloads

Google Chrome Golf 6
 © Internet, books, teachers and Rudevich Alexander brains.