Date math without the dates

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. :slight_smile:

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?

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

On Apr 13, 11:23 pm, Daniel W. [email protected] wrote:

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


Posted viahttp://www.ruby-forum.com/.

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

Chris S. wrote:

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