Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created September 23, 2022 12:32
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 qoobaa/f588a6c31bea77ca8396dfe8adedb466 to your computer and use it in GitHub Desktop.
Save qoobaa/f588a6c31bea77ca8396dfe8adedb466 to your computer and use it in GitHub Desktop.
def speak_hour(hour)
hour = 0 if hour == 24
{
0 => "midnight",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
6 => "six",
7 => "seven",
8 => "eight",
10 => "ten",
11 => "eleven",
12 => "twelve"
#...
}.fetch(hour)
end
def speak_minutes(minutes)
{
5 => "five",
10 => "ten",
15 => "quarter",
20 => "twenty",
25 => "twenty five",
32 => "thirty two"
}.fetch(minutes)
end
def speak(time)
hour, minutes = time.split(":").map(&:to_i)
if hour.zero? and minutes.zero?
speak_hour(hour)
elsif hour == 12 and minutes.zero?
"noon"
elsif minutes.zero?
"#{speak_hour(hour)} o'clock"
elsif minutes < 30
"#{speak_minutes(minutes)} past #{speak_hour(hour)}"
elsif minutes == 30
"half past #{speak_hour(hour)}"
elsif minutes > 30 and !minutes.modulo(5).zero?
"#{speak_hour(hour)} #{speak_minutes(minutes)}"
else
"#{speak_minutes(60 - minutes)} to #{speak_hour(hour + 1)}"
end
end
require 'minitest/autorun'
require_relative 'clock'
class ClockTest < Minitest::Test
def test_works_with_1_00
assert_equal "one o'clock", speak('1:00')
end
def test_works_with_2_05
assert_equal "five past two", speak('2:05')
end
def test_works_with_3_10
assert_equal "ten past three", speak('3:10')
end
def test_works_with_4_15
assert_equal "quarter past four", speak('4:15')
end
def test_works_with_6_25
assert_equal "twenty five past six", speak('6:25')
end
def test_works_with_6_32
assert_equal "six thirty two", speak('6:32')
end
def test_works_with_7_30
assert_equal "half past seven", speak('7:30')
end
def test_works_with_7_35
assert_equal "twenty five to eight", speak('7:35')
end
def test_works_with_7_40
assert_equal "twenty to eight", speak('7:40')
end
def test_works_with_9_45
assert_equal "quarter to ten", speak('9:45')
end
def test_works_with_10_50
assert_equal "ten to eleven", speak('10:50')
end
def test_works_with_11_55
assert_equal "five to twelve", speak('11:55')
end
def test_works_with_00_00
assert_equal "midnight", speak('00:00')
end
def test_works_with_12_00
assert_equal "noon", speak('12:00')
end
def test_works_with_23_55
assert_equal "noon", speak('23:55')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment