On Mar 24, 2010, at 11:35 PM, Alex Baranosky wrote:

> I want to be able to have an object extend Enumerable in Ruby to be an
> infinite list of Mondays (for example).
>
> So it would yield: March 29, April 5, April 12...... etc
>
> How can I implement this in Ruby?
> --  
> Posted via http://www.ruby-forum.com/.
>


require 'date'
class Mondays
   include Enumerable

   def initialize(starting=Date.today)
     @monday = starting
     @monday += 1 until @monday.wday == 1
   end

   def succ
     @monday += 7
   end

   def each
     place = @monday.dup
     loop do
       yield place
       place += 7
     end
   end
end

new_week = Mondays.new
# => #<Mondays:0x357938 @monday=#<Date: 4910569/2,0,2299161>>

puts new_week
# #<Mondays:0x357938>
# => nil

new_week.each do |day|
   puts day
   break if day > Date.civil(2010,4,30)
end
# 2010-03-29
# 2010-04-05
# 2010-04-12
# 2010-04-19
# 2010-04-26
# 2010-05-03
# => nil

But don't try to call #to_a on that new_week object or you'll find out  
that an infinite sequence takes quite a long time to iterate.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com