public
Last active

  • Download Gist
average_time_of_day.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# A horribly scrappy "just for fun" entry into Satish Talim's latest Ruby
# challenge. Didn't want to use any libraries, etc, just bashed at it true 1980s style!
# It makes the assumption, as was raised in several comments, that the first time in
# the array is the first of the "block" of times..
 
def average_time_of_day(times)
pr = nil
times.map! do |t|
h,m = t.scan(/\d+/).map(&:to_i)
h += 12 if t =~ /pm/ || (pr && h < pr)
pr = h
h + m / 60.0
end
mean = times.reduce(:+) / times.size
h = mean.to_i
m = sprintf("%0.2d", ((mean - h) * 60.0).round)
"#{h > 12 ? h - 12 : h}:#{m}#{ h > 12 && h != 24 ? 'pm' : 'am' }"
end
 
raise unless average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"]) == "12:01am"
raise unless average_time_of_day(["6:41am", "6:51am", "7:01am"]) == "6:51am"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.