From: David Masover Date: 2010-03-25T13:03:25+09:00 Subject: Re: How to create an infinite enumerable of Times? On Wednesday 24 March 2010 10:35:16 pm Alex Baranosky wrote: > infinite list of Mondays (for example). > > So it would yield: March 29, April 5, April 12...... etc > > How can I implement this in Ruby? First learn to implement Enumerable, then it should be obvious. All you need to do is define a #each method. So, for example, here's an implementation of all numbers: class PositiveIntegers include Enumerable def each i = 1 while true yield i i += 1 end end end If you can figure out how to do a similar loop for Mondays, you can do that. Keep in mind that this kind of thing isn't nearly as cool in practice as you might like -- for one, a lot of the reasons you'd want an enumerable are not going to work well. For example, calling .map{...}.each is probably going to result in an infinite loop, as map returns an array. I would probably do it like this: module Foo def self.positive_integers return enum_for(:positive_integers) unless block_given? i = 1 while true yield i i += 1 end end end So that means you could do this: Foo.positive_integers { ... } Or, that enum_for means you could also do this: Foo.positive_integers.each { ... }