This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Method Check: Date#succ
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
Date#succ has saved the day for me in calendaring operations. I was Duck Hunting and simply guessed it was there. (Someone should put together a Duck Typer’s Handbook that just contains the commonly reused method names and their presumed meanings.)
Basically, I want to rave about Ruby’s Date class, autonomous from Time. I had a table of rows which represented individual dates. I needed to take that table and build date ranges.
I’ll simplify by posing the problem as an event calendar.
events = {}
sqlq = "SELECT title, event_date FROM events ORDER BY event_date ASC"
db.query( sqlq ).each_hash do |event|
date_e = Date.new( *event['event_date'].split('-').map { |n| n.to_i } )
events[event['title']] ||= []
last_e = events[event['title']].last
if last_e
if last_e[1].succ == date_e
last_e[1] += 1
next
end
end
events[event['title']] << [date_e] * 2
end
I’ll draw your attention to two lines. The last_e[1].succ and the last_e[1] += 1 lines. I’m building a Date range with a start and end date. So, last_e[1] represents the end date.
The line last_e[1].succ == date_e compares the day after the end date with the date from the database. If they match, then we know the date is the next date in the series.
The following line, last_e[1] += 1 adds a single day to the end date. Date math works really nicely like that. (Now, I’ll ask you how you prefer to add months and years.)