Задача Military Time из SoloLearn Ruby
Условие: You want to convert the time from a 12 hour clock to a 24 hour clock. If you are given the time on a 12 hour clock, you should output the time as it would appear on a 24 hour clock.
Task:
Determine if the time you are given is AM or PM, then convert that value to the way that it would appear on a 24 hour clock.
Input Format: A string that includes the time, then a space and the indicator for AM or PM.
Output Format: A string that includes the time in a 24 hour format (XX:XX)
Sample Input: 1:15 PM
Sample Output: 13:15
Вот, то, что я написал, проваливается на 3 и 5 тестах Заранее прошу прощение за код без пробелов SoloLearn сжал
time = gets.chomp.split
h_a_m = time[0].split(":")
hours = h_a_m[0].to_i
if time[1] == "AM"
if hours == 12
hours = "0"
h_a_m[0] = hours
arr = h_a_m.join(":")
puts arr
else
puts time[0]
end
else
if hours == 12
hours = hours.to_s
h_a_m[0] = hours
arr = h_a_m.join(":")
puts arr
else
hours += 12
hours = hours.to_s
h_a_m[0] = hours
arr = h_a_m.join(":")
puts arr
end
end
´´´
Ответы (1 шт):
Автор решения: Taras
→ Ссылка
require 'time'
input = '1:05 PM'
result = Time.strptime(input, "%l:%M %p").strftime("%H:%M")
puts result