Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 3 - Iterators in Ruby
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

Iterators in Ruby
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2007-03-08

    Table of Contents:
  • Iterators in Ruby
  • 7.5 Writing an Iterator Over a Data Structure
  • 7.6 Changing the Way an Object Iterates
  • 7.7 Writing Block Methods That Classify or Collect

  • 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


    Iterators in Ruby - 7.6 Changing the Way an Object Iterates


    (Page 3 of 4 )

    Problem

    You want to use a data structure as an Enumerable, but the object’s implementation of #eachdoesn’t iterate the way you want. Since all ofEnumerable’s methods are based oneach, this makes them all useless to you.

    Discussion

    Here’s a concrete example: a simple array.

      array = %w{bob loves alice}
      array.collect { |x| x.capitalize }
      # => ["Bob", "Loves", "Alice"]

    Suppose we want to callcollect on this array, but we don’t wantcollectto useeach: we want it to usereverse_each. Something like this hypotheticalcollect_ reversemethod:

      array.collect_reverse { |x| x.capitalize }
     
    # => ["Alice", "Loves", "Bob"]

    Actually defining acollect_reversemethod would add significant new code and only solve part of the problem. We could overwrite the array’seach implementation with a singleton method that callsreverse_each, but that’s hacky and it would surely have undesired side effects.

    Fortunately, there’s an elegant solution with no side effects: wrap the object in anEnumerator. This gives you a new object that acts like the old object would if you’d swapped out itseachmethod:

      require 'enumerator'
      reversed_array = array.to_enum(:reverse_each)
      reversed_array.collect { |x| x.capitalize }
      # => ["Alice", "Loves", "Bob"]

      reversed_array.each_with_index do |x, i|
       
    puts %{#{i}=>"#{x}"}
      end
      # 0=>"alice"
      # 1=>"loves"
      # 2=>"bob"

    Note that you can’t use theEnumeratorfor our array as though it were the actual array. Only the methods ofEnumerableare supported:

      reversed_array[0]
      # NoMethodError: undefined method `[]' for #<Enumerable::Enumerator:0xb7c2cc8c>

    Discussion

    Whenever you’re tempted to reimplement one of the methods of Enumerable, try using an Enumerator instead. It’s like modifying an object’seach method, but it doesn’t affect the original object.

    This can save you a lot of work. Suppose you have a tree data structure that provides three different iteration styles:each_prefix,each_postfix, andeach_infix. Rather than implementing the methods ofEnumerablefor all three iteration styles, you can leteach_ prefixbe the default implementation ofeach, and calltree.to_enum(:each_postfix)ortree.to_enum(:each_infix)if you need anEnumerablethat acts differently.

    A single underlying object can have multiple Enumerable objects. Here’s a second Enumerablefor our simple array, in whicheach acts likeeach_with_indexdoes for the original array:

     

      array_with_index = array.enum_with_index
      array_with_index.each do |x, i|
       
    puts %{#{i}=>"#{x}"}
      end
      # 0=>"bob"
      # 1=>"loves"
      # 2=>"alice"

      array_with_index.each_with_index do |x, i|
       
    puts %{#{i}=>#{x.inspect}}
      end
      # 0=>["bob", 0]
      # 1=>["loves", 1]
      # 2=>["alice", 2]

    When yourequire 'enumerator',Enumerable sprouts two extra enumeration methods,each_consandeach_slice. These make it easy to iterate over a data structure in chunks. An example is the best way to show what they do:

      sentence = %w{Well, now I've seen everything!}

      two_word_window = sentence.to_enum(:each_cons, 2)
      two_word_window.each { |x| puts x.inspect }
      # ["Well,", "now"]
      # ["now", "I've"]
      # ["I've", "seen"]
      # ["seen", "everything!"]

      two_words_at_a_time = sentence.to_enum(:each_slice, 2)
      two_words_at_a_time.each { |x| puts x.inspect }
      # ["Well,", "now"]
      # ["I've", "seen"]
      # ["everything!"]

    Note how any arguments passed intoto_enumare passed along as arguments to the iteration method itself.

    In Ruby 1.9, theEnumerable::Enumeratorclass is part of the Ruby core; you don’t need therequirestatement. Also,each_consandeach_sliceare built-in methods ofEnumerable.

    See Also

    1. Recipe 7.9, “Looping Through Multiple Iterables in Parallel”
    2. Recipe 20.6, “Running a Code Block on Many Objects Simultaneously”

    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

    - 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