Misleading DateTime comparison

12 views
Skip to first unread message

Nate Sullivan

unread,
Dec 1, 2017, 1:23:02 AM12/1/17
to Ruby on Rails: Talk
I think the most natural way read the code created_at < 10.minutes.ago is "created_at is less than ten minutes ago," but that reading suggests the mistaken interpretation that created_at is fewer than ten minutes ago. The correct interpretation is that created_at is earlier than ten minutes ago. Is there a better way to write the same comparison?

I've thought of three potential improvements so far:
  • 10.minutes.ago > created_at  This "Yoda condition" style doesn't have a translation into ordinary English that tempts you into misunderstanding. But Yoda conditions are inconsistent with the rest of the comparisons in my codebase.
  • Time.now > 10.minutes.after(created_at)  This is another style of Yoda condition. This one allows people who misread the operator (as "more than ten minutes after created_at" instead of "later than ten minutes after created_at") to correctly predict the actual behavior, but for the wrong reason.
  • created_at.earlier_than?(10.minutes.ago)  The ordinary English translation (created_at is earlier than ten minutes ago) is correct. But this requires monkeypatching DateTime (or using the human_time gem) to add the earlier_than? method, which I'd prefer not to do.
Is there a better way that avoids Yoda conditionals, monkeypatching and extra gems?

Thanks for the consideration,
Nate

Colin Law

unread,
Dec 1, 2017, 3:57:05 AM12/1/17
to Ruby on Rails: Talk
On 1 December 2017 at 05:49, Nate Sullivan
<nathaniel...@gmail.com> wrote:
> I think the most natural way read the code created_at < 10.minutes.ago is
> "created_at is less than ten minutes ago," but that reading suggests the
> mistaken interpretation that created_at is fewer than ten minutes ago. The
> correct interpretation is that created_at is earlier than ten minutes ago.

It never occurred to me that there is any confusion over this syntax.
created_at is a time, 10 minutes ago is a time, time a < time b is
unambiguous.

Colin

Mr Nine

unread,
Dec 2, 2017, 4:32:17 AM12/2/17
to Ruby on Rails: Talk
On Thursday, November 30, 2017 at 10:23:02 PM UTC-8, Nate Sullivan wrote:
> I think the most natural way read the code created_at < 10.minutes.ago is "created_at is less than ten minutes ago," but that reading suggests the mistaken interpretation that created_at is fewer than ten minutes ago. The correct interpretation is that created_at is earlier than ten minutes ago. Is there a better way to write the same comparison?
>
>
>

I think the real issue is that English lacks strong typing and so the comparison operater is imprecise.
Reply all
Reply to author
Forward
0 new messages