JP.
JP.

Reputation: 5606

Ruby date today? - unexpected behavior

I'm new to Ruby and am trying to figure out why the following doesn't work as expected:

2.2.1 :010 > user_date = Date.today
 => Sun, 31 May 2015 
2.2.1 :011 > user_date.today?
 => false 

I'm using the Rails console and the commands are executed one after the other (with maybe a second between executions). I'm sure there is nuance that I'm not understanding, but shouldn't the second command return true instead of false? If not, why? Thanks in advance!

Edit #1 - Additional information requested by Arup

 2.2.1 :013 > puts user_date.method(:today?).owner
DateAndTime::Calculations
 => nil 

Edit #2 - So I had a hunch. I'm on US Eastern time and it was coming up to midnight when I ran into the original issue. I waited for the turn of midnight, and now the following works.

2.2.1 :004 > user_date = Date.today
 => Mon, 01 Jun 2015 
2.2.1 :005 > user_date.today?
 => true 

Upvotes: 4

Views: 162

Answers (1)

fylooi
fylooi

Reputation: 3870

Date.today belongs to core Ruby while today? belongs to Rails.

Under the hood, today? calls Date.current(Rails as well) instead of Date.today.

Going a bit further, we find that Date.current takes the current Rails time zone into account if one is configured. That should be the source of your mismatch.

Upvotes: 7

Related Questions