Class: IntTime

Inherits:
Object
  • Object
show all
Defined in:
lib/int_time.rb

Constant Summary collapse

MAX_HOUR =
24
MAX_MINUTE =
60
TIME_PATTERN =
/(\d{2}):(\d{2})/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hour, minute) ⇒ IntTime

Returns a new instance of IntTime.



8
9
10
11
# File 'lib/int_time.rb', line 8

def initialize(hour, minute)
  @hour = hour
  @minute = minute
end

Instance Attribute Details

#hourObject (readonly)

Returns the value of attribute hour.



2
3
4
# File 'lib/int_time.rb', line 2

def hour
  @hour
end

#minuteObject (readonly)

Returns the value of attribute minute.



2
3
4
# File 'lib/int_time.rb', line 2

def minute
  @minute
end

Class Method Details

.from(token) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# 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

.to_int(time) ⇒ Object



91
92
93
# File 'lib/int_time.rb', line 91

def self.to_int(time)
  from(time).to_i
end

.to_str(time) ⇒ Object



87
88
89
# File 'lib/int_time.rb', line 87

def self.to_str(time)
  from(time).to_s
end

.valid?(number) ⇒ Boolean

Class Methods ##

Returns:

  • (Boolean)


48
49
50
51
52
53
# 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

Instance Method Details

#+(other) ⇒ Object

Instance Methods ##



18
19
20
21
22
# 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) ⇒ Object



30
31
32
33
# 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) ⇒ Object



24
25
26
27
28
# 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_iObject



35
36
37
# File 'lib/int_time.rb', line 35

def to_i
  @hour * 100 + @minute
end

#to_sObject



39
40
41
# File 'lib/int_time.rb', line 39

def to_s
  format('%02d:%02d', @hour, @minute)
end