Shouldn't ranges work for datetime fields

I figure ranges should work just fine for a datetime. I want to weight
a total based on how recently an item was created. Using the case
statement, I check various ranges. I simply cannot get this to work:

    weighted_total +=
      case item.created_at
        when Time.now...24.hours.ago:      20
        when 24.hours.ago...48.hours.ago:  8
        when 48.hours.ago...1.week.ago:    4
        when 1.week.ago...2.weeks.ago:     2
        when 2.weeks.ago...4.weeks.ago:    1
        else                               0
      end

Every “created_at” field resolve to the else case.

I also tried it with if statements and Time.now…24.hours.ago ===
item.created at boolean expressions. In that case, every single if
statement was successful, regardless of the range.

I’m sure I’m simply missing some intricacy with date handling. Every
language seems to have its gotchas in this realm.

bjhess wrote:

        when 2.weeks.ago...4.weeks.ago:    1

language seems to have its gotchas in this realm.
Try reversing the order of your ranges so that the oldest time is
defined first…

case item.created_at
when 24.hours.ago … Time.now: 20
when 48.hours.ago … 24.hours.ago: 4

end

_Kevin

Thanks, _Kevin. You’re a life saver!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs