'How does Ruby's ActiveSupport "between?" function handle impossible times?
I'm using the ActiveSupport between? to determine if a time is between 8 AM and 4:45 PM, and I accidentally was putting a later time as the first argument and the earlier time as the second, like so:
# variable `time` gets set up here
unless time.between?(Time.local(time.year, time.month, time.day, 8), Time.local(time.year, time.month, time.day, 4, 45))
# short circuit
end
# do stuff
I know this is wrong since I should have it use 16, 45 instead of 4, 45 so I was able to fix the bug, but I couldn't find documentation on what happens in this case, since it wasn't throwing any errors which was strange to me. It seemed that it was always returning true, since the inside of this unless statement never executed during testing, which was bizarre, unexpected behavior to me. I would assume it would either throw some error or always return false, since technically no time can be between 8 AM and 4:45 AM.
So how does the between? function actually handle times that are "impossible", e.g. the later time comes before the earlier time?
Solution 1:[1]
It always returns false, not true. You can try yourself with every number for hours:
my_time = Time.local(2022, 05, 8, 6)
eight = Time.local(2022, 05, 8, 8)
four = Time.local(2022, 05, 8, 4)
puts my_time.between?(eight, four)
and will always return false
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
