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

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.