class IntTime

Constants

MAX_HOUR
MAX_MINUTE
TIME_PATTERN

Attributes

hour[R]
minute[R]

Public Class Methods

from(token) click to toggle source
# File lib/int_time.rb, line 55
def self.from(token)
  if token.class <= Integer
    from_int(token)
  elsif token.class <= String
    from_str(token)
  elsif token.class <= Time
    from_time(token)
  else
    raise "Invalid input: #{token}; expect integer or string"
  end
end
new(hour, minute) click to toggle source
# File lib/int_time.rb, line 8
def initialize(hour, minute)
  @hour = hour
  @minute = minute
end
to_int(time) click to toggle source
# File lib/int_time.rb, line 91
def self.to_int(time)
  from(time).to_i
end
to_str(time) click to toggle source
# File lib/int_time.rb, line 87
def self.to_str(time)
  from(time).to_s
end
valid?(number) click to toggle source

Class Methods ##

# File lib/int_time.rb, line 48
def self.valid?(number)
  number.is_a?(Integer) &&
    number >= 0 &&
    valid_hour?(number % 10_000 / 100) &&
    valid_minute?(number % 100)
end

Private Class Methods

from_int(time) click to toggle source
# File lib/int_time.rb, line 67
def self.from_int(time)
  raise "Input #{time} is not a valid int time" unless valid?(time)
  IntTime.new(time % 10_000 / 100 % MAX_HOUR, time % 100 % MAX_MINUTE)
end
from_str(time) click to toggle source
# File lib/int_time.rb, line 73
def self.from_str(time)
  match = TIME_PATTERN.match(time)
  if match.nil? || match.size != 3
    raise "Input #{time} is not a valid string time"
  end
  IntTime.new(match[1].to_i, match[2].to_i)
end
from_time(time) click to toggle source
# File lib/int_time.rb, line 82
def self.from_time(time)
  IntTime.new(time.hour, time.min)
end
valid_hour?(number) click to toggle source
# File lib/int_time.rb, line 95
def self.valid_hour?(number)
  number.is_a?(Integer) && number < MAX_HOUR && number >= 0
end
valid_minute?(number) click to toggle source
# File lib/int_time.rb, line 100
def self.valid_minute?(number)
  number.is_a?(Integer) && number < MAX_MINUTE && number >= 0
end

Public Instance Methods

+(other) click to toggle source

Instance Methods ##

# File lib/int_time.rb, line 18
def +(other)
  new_minute = @minute + other.minute
  new_hour = @hour + other.hour + new_minute / MAX_MINUTE
  IntTime.new(new_hour % MAX_HOUR, new_minute % MAX_MINUTE)
end
add_hour(hour) click to toggle source
# File lib/int_time.rb, line 30
def add_hour(hour)
  new_hour = @hour + hour
  IntTime.new(new_hour % MAX_HOUR, @minute)
end
add_minute(minute) click to toggle source
# File lib/int_time.rb, line 24
def add_minute(minute)
  new_minute = @minute + minute
  new_hour = @hour + new_minute / MAX_MINUTE
  IntTime.new(new_hour % MAX_HOUR, new_minute % MAX_MINUTE)
end
to_i() click to toggle source
# File lib/int_time.rb, line 35
def to_i
  @hour * 100 + @minute
end
to_s() click to toggle source
# File lib/int_time.rb, line 39
def to_s
  format('%02d:%02d', @hour, @minute)
end