views:

122

answers:

5

Open up a Rails console and enter this:

2.weeks.ago.between? 2.weeks.ago, 1.week.ago

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

 Date.yesterday.between? Date.yesterday, Date.tomorrow
+4  A: 

The cause is undoubtedly due to the resolution of the time function. Sometimes the two instances of 2.weeks.ago resolve to the same time and sometimes they don't. When you use yesterday you don't see the issue because it always resolves to zero hour instead of relative to the current time.

In a case like yours you probably only want to compare the date, not the date and time.

tvanfosson
+1  A: 

tvanfosson, hit it on the head.

2.weeks.ago gives you a time exactly two weeks from the execution to the millisecond. So evaluating it twice could provide two different times.

Doing something like the following would give you consistent results:

two_weeks_ago = 2.weeks.ago
two_weeks_ago.between? two_weeks_ago, 1.week.ago
Tony Fontenot
+1  A: 

I just tried this and got false every time. What is the intent behind this question? I ask b/c I do date comparisons like this at the DB level.

Bill
Hmm, I thought my intent was quite obviously described - the failing test cases. I am getting this problem on a Windows box; perhaps that is the reason.
Jaryl
A: 

Definitely due to the fact thwt 2.weeks.ago is called twice, each time returning a different response, due to processing time. But does it matter. The between function works exactly as intended. The behaviour is not weird because if you stepped into the code with a debugger, you would see it operating exactly as it should.

Kibbee
Yes, it works this way by design. But I was caught off-guard knowing if it was doing equal-or comparisons.
Jaryl
A: 

Try doing:

two_weeks_ago = 2.weeks.ago.to_date
two_weeks_ago.between? two_weeks_ago, 1.week.ago
Ryan Bigg