clock.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Date-independent clock
class Clock
  VERSION = 1

  # Create a new clock
  def self.at(hour, minute)
    Clock.new(hour, minute)
  end

  # Representation of the time
  def to_s
    format('%02d:%02d', hour, minute)
  end

  # Return a new clock with minutes added
  def +(other)
    Clock.new(hour, minute + other)
  end

  # Compare to another clock
  def ==(other)
    @minutes == other.minutes
  end

  # Get the hour
  def hour
    @minutes / 60
  end

  # Get the minute
  def minute
    @minutes % 60
  end

  protected

  attr_reader :minutes

  private

  def initialize(hour, minute)
    # Store the total number of minutes
    # Make sure things wrap around at day boundaries
    @minutes = (hour * 60 + minute) % (24 * 60)
  end
end

Comments


You're not logged in right now. Please login via GitHub to comment