Today I Learned

hashrocket A Hashrocket project

How to take next elements with Enumerator

So we had this logic to get the next 10 Tuesdays and Thursdays:

date = Time.current
(1..10).map { date = next_available_day(date) }

def next_available_day(date)
  loop { return date if tuesday_or_thursday?(date += 1.day) }
end

def tuesday_or_thursday?(date)
  date.wday == 2 || date.wday == 4
end

With Enumerator it seems cleaner:

next_available_dates(Time.current).take(10)

def next_available_dates(date)
  Enumerator.new do |enumerator|
    loop { enumerator.yield date if tuesday_or_thursday?(date += 1.day) }
  end
end

def tuesday_or_thursday?(date)
  date.wday == 2 || date.wday == 4
end

h/t by @mwoods79

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.