Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Last active February 27, 2016 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durrellchamorro/035d2f0be02bf44b1b40 to your computer and use it in GitHub Desktop.
Save durrellchamorro/035d2f0be02bf44b1b40 to your computer and use it in GitHub Desktop.
Clock Exercise Solution
class Clock
attr_accessor :hours, :minutes
def initialize(hours, minutes)
@hours, @minutes = hours, minutes
end
def self.at(hours=0, minutes=0)
new(hours, minutes)
end
def to_s
"#{format(@hours)}:#{format(@minutes)}"
end
def +(minutes)
minutes.times do
@minutes += 1
change_hour_and_adjust_minutes(:+, 1) if @minutes == 61
@hours = 0 if wrap_around?
end
self
end
def -(minutes)
minutes.times do
@minutes -= 1
change_hour_and_adjust_minutes(:-, 59) if @minutes == -1
@hours = 23 if wrap_around?
end
self
end
def ==(other)
@minutes == other.minutes && @hours == other.hours
end
private
def format(hours_or_minutes)
result = "00"
result << hours_or_minutes.to_s
result = result.slice(-2..-1)
end
def change_hour_and_adjust_minutes(operation, minutes)
@hours = @hours.send(operation, 1)
@minutes = minutes
end
def wrap_around?
@hours == -1 || @hours == 24
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment