Created
May 31, 2019 20:37
-
-
Save havenwood/ae64b281cb05d4aa15799e5c354252d8 to your computer and use it in GitHub Desktop.
A TimeOfDay class for leftylink on IRC
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
# frozen_string_literal: true | |
class TimeOfDay | |
include Comparable | |
SEPARATOR = ':' | |
HOURS_MATCH = /\A\d+/.freeze | |
MINUTES_MATCH = /(?<=#{SEPARATOR})\d+/o.freeze | |
attr_reader :hour | |
attr_reader :minute | |
def self.[](time) | |
unless time.respond_to? :to_str | |
raise TypeError, "no implicit conversion of #{time.class} into String" | |
end | |
time_str = time.to_str | |
new hour: time_str[HOURS_MATCH].to_i, minute: time_str[MINUTES_MATCH].to_i | |
end | |
def initialize(hour:, minute:) | |
@hour = hour | |
@minute = minute | |
freeze | |
end | |
def <=>(other) | |
to_i <=> other.to_i | |
end | |
def to_s | |
"#{hour}#{SEPARATOR}#{minute}" | |
end | |
def to_i | |
@hour * 60 + @minute | |
end | |
def +(other) | |
hours, minutes = (to_i + other).divmod(60) | |
self.class.new hour: hours, minute: minutes | |
end | |
def -(other) | |
hours, minutes = (to_i - other).divmod(60) | |
self.class.new hour: hours, minute: minutes | |
end | |
def succ | |
self + 1 | |
end | |
end | |
before = TimeOfDay['12:00'] | |
#=> #<TimeOfDay:0x0000000114e43490 @hour=12, @minute=0> | |
after = TimeOfDay['12:05'] | |
#=> #<TimeOfDay:0x0000000115305050 @hour=12, @minute=5> | |
before < after | |
#=> true | |
(before..after).count | |
#=> 6 | |
before - 42 | |
#=> #<TimeOfDay:0x00000001153435f8 @hour=11, @minute=18> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment