Created
August 24, 2015 19:25
-
-
Save richardkmichael/c3f9251630f7da63fbe7 to your computer and use it in GitHub Desktop.
Broken DateTime based Range#include?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[38] pry(main)> RUBY_DESCRIPTION | |
=> "ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin12.0]" | |
[41] pry(main)> d = "2015-01-01" | |
=> "2015-01-01" | |
# Broken Range#include? with DateTime objects, they don't understand the time portion of the day. | |
[42] pry(main)> n = DateTime.parse "#{d} 9am" | |
=> #<DateTime: 2015-01-01T09:00:00+00:00 ((2457024j,32400s,0n),+0s,2299161j)> | |
[43] pry(main)> f = DateTime.parse "#{d} 5pm" | |
=> #<DateTime: 2015-01-01T17:00:00+00:00 ((2457024j,61200s,0n),+0s,2299161j)> | |
[44] pry(main)> (n..f).include? DateTime.parse "#{d} 12pm" | |
=> false | |
# Oops, need stdlib's time for #parse(). | |
[45] pry(main)> Time.parse d | |
NoMethodError: undefined method `parse' for Time:Class | |
[47] pry(main)> require 'time' | |
=> true | |
[50] pry(main)> n = Time.parse "#{d} 9am" | |
=> 2015-01-01 09:00:00 -0500 | |
[51] pry(main)> f = Time.parse "#{d} 5pm" | |
=> 2015-01-01 17:00:00 -0500 | |
[53] pry(main)> noon = Time.parse "#{d} 12pm" | |
=> 2015-01-01 12:00:00 -0500 | |
# Range cannot iterate with Time objects.. | |
[54] pry(main)> (n..f).include? Time.parse "#{d} 12pm" | |
TypeError: can't iterate from Time | |
from (pry):53:in `each' | |
# So test it old-school " <= && <= ". | |
[55] pry(main)> n <= noon && noon <= f | |
=> true | |
[56] pry(main)> eight = Time.parse "#{d} 8pm" | |
=> 2015-01-01 20:00:00 -0500 | |
[57] pry(main)> n <= eight && eight <= f | |
=> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment