Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 2 - Code Blocks and 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  
Mobile Linux 
App Generation ROI 
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

Code Blocks and Iteration
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2007-03-01

    Table of Contents:
  • Code Blocks and Iteration
  • 7.1 Creating and Invoking a Block
  • 7.2 Writing a Method That Accepts a Block
  • 7.3 Binding a Block Argument to a Variable

  • 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
     
     
    ADVERTISEMENT


    Code Blocks and Iteration - 7.1 Creating and Invoking a Block


    (Page 2 of 4 )

    Problem

    You want to put some Ruby code into an object so you can pass it around and call it later.

    Solution

    By this time, you should familiar with a block as some Ruby code enclosed in curly brackets. You might think it possible to define a block object as follows: 

      aBlock = { |x| puts x }      # WRONG

      # SyntaxError: compile error

    That doesn’t work because a block is only valid Ruby syntax when it’s an argument to a method call. There are several equivalent methods that take a block and return it as an object. The most favored method isKernel#lambda:*

      aBlock = lambda { |x| puts x }    # RIGHT

    To call the block, use thecallmethod:

      aBlock.call "Hello World!"
     
    # Hello World!

    Discussion

    The ability to assign a bit of Ruby code to a variable is very powerful. It lets you write general frameworks and plug in specific pieces of code at the crucial points.

    As you’ll find out in Recipe 7.2, you can accept a block as an argument to a method by prepending&to the argument name. This way, you can write your own trivial version of thelambdamethod:

      def my_lambda(&aBlock)
        aBlock
      end

      b = my_lambda { puts "Hello World My Way!" }
     
    b.call
     
    # Hello World My Way!

    A newly defined block is actually aProcobject.

      b.class                   # => Proc

    You can also initialize blocks with theProcconstructor or the methodKernel#proc. The methodsKernel#lambda,Kernel#proc, andProc.newall do basically the same thing. These three lines of code are nearly equivalent:

      aBlock = Proc.new { |x| puts x }
      aBlock = proc { |x| puts x }
      aBlock = lambda { |x| puts x }

    What’s the difference?Kernel#lambdais the preferred way of creating block objects, because it gives you block objects that act more like Ruby methods. Consider what happens when you call a block with the wrong number of arguments:

      add_lambda = lambda { |x,y| x + y }

      add_lambda.call(4)
      # ArgumentError: wrong number of arguments (1 for 2)

      add_lambda.call(4,5,6)
      # ArgumentError: wrong number of arguments (3 for 2)

    A block created withlambdaacts like a Ruby method. If you don’t specify the right number of arguments, you can’t call the block. But a block created withProc.newacts like the anonymous code block you pass into a method likeEnumerable#each:

      add_procnew = Proc.new { |x,y| x + y }

      add_procnew.call(4)
      # TypeError: nil can't be coerced into Fixnum

      add_procnew.call(4,5,6)            # => 9

    If you don’t specify enough arguments when you call the block, the rest of the arguments are givennil. If you specify too many arguments, the extra arguments are ignored. Unless you want this kind of behavior, uselambda.

    In Ruby 1.8,Kernel#procacts likeKernel#lambda. In Ruby 1.9,Kernel#procacts likeProc.new, as better befits its name.

    See Also
    1. Recipe 7.2, “Writing a Method That Accepts a Block”
    2. Recipe 10.4, “Getting a Reference to a Method”

    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 seven 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

    - Iterating and Incrementing Strings in Ruby
    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - 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






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT