O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing Iterator Methods

Standard Ruby iterators cover so many situations that you don't often have to write your own. Inheritance sees to it that any class descending from a common container class like String, Array, Hash, or Range will have a working each method. But many classes contain other containers without being descended from them; often it is useful to provide iterators that link those inner containers to the outside world:

class Foo
  def initialize
    @my_data = %w{ Washington Adams Jefferson }
  end
  def each
    @my_data.each {|element| yield element}
  end
end
Foo.new.each {|x| puts x}
  # output:  Washington
						Adams
						Jefferson
					

Foo is not a descendant of the Array class, but Foo#each allows Foo objects to be iterated upon just as if they were arrays. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required