Home arrow Ruby-on-Rails arrow Page 3 - Iterators in Ruby
RUBY-ON-RAILS

Iterators in Ruby


In this second part of a three-part article, we continue our discussion of code blocks and begin focusing on iterators as well. It 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 08, 2007
TABLE OF CONTENTS:
  1. · Iterators in Ruby
  2. · 7.5 Writing an Iterator Over a Data Structure
  3. · 7.6 Changing the Way an Object Iterates
  4. · 7.7 Writing Block Methods That Classify or Collect

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

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”


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- 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
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



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