Date math without the dates...

D

Daniel Waite

Hi all. Observe:

(Date.today..Date.today + 90).to_a.size # ~90

That operation is, unfortunately, slow. Well, when you're calling it
100+ times it's slow. :)

Is there a way to get at the result of that operation (an integer) with
two date objects? e.g.

class AccountTransaction

attr_accessor :posted

def day_count(date)
(posted..date).to_a.size
end

end

Any ideas?
 
D

Daniel Waite

Ack, some amendments...

Is there _another_ way to get at the result of that operation (an
integer) besides the one I posted above?

And, I suppose a better title would have been "Faster date math."
 
C

Chris Shea

Ack, some amendments...

Is there _another_ way to get at the result of that operation (an
integer) besides the one I posted above?

And, I suppose a better title would have been "Faster date math."

irb(main):001:0> ((Date.today + 90) - Date.today).to_i
=> 90

Subtracting Dates from each other returns a Rational.

irb(main):002:0> (Date.today + 90) - Date.today
=> Rational(90, 1)

You can just coerce that into an integer. No intermediate Array
required.

HTH,
Chris
 
D

Daniel Waite

Chris said:
You can just coerce that into an integer. No intermediate Array
required.

Ah, sweet! Crazy, too: I _just_ tried subtracting dates and found that a
Rational was returned, but didn't know you could coerce it into an
integer. Thanks so much Chris! (And yes, it's _much_ faster!)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,216
Messages
2,571,120
Members
47,722
Latest member
Alexcarry541

Latest Threads

Top