The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Method Check: Date#succ

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Method Check: Date#succ Posted: Mar 24, 2005 10:58 AM
Reply to this message Reply

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
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded

Advertisement

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

And, even better, Date objects inside of a Range.

 >> require 'date'
 >> D = proc { |*d| Date.new(*d) }
 >> (D[2004, 1, 1]..D[2004, 1, 12]).include? D[2004, 5, 6]
 => false
 >> (D[2004, 1, 1]..D[2004, 1, 12]).include? D[2004, 1, 6]
 => true

Read: Method Check: Date#succ

Topic: Rails and RIFE, Wars and Strife... It's All A Buncha To-do!! Previous Topic   Next Topic Topic: Relevance, Recency And The Rules Of Blogging

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use