Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Solution to RPCFN #2
module AverageTimeOfDay
require 'date'
# Assumes times_of_day is an array of valid time strings in chronological
# order.
def average_time_of_day(times_of_day)
# Convert times_of_day to an array of Time objects, ensuring that times
# are in chronological order by adding a day if the the time of the
# current iteration is earlier than the last iterated time.
times = times_of_day.inject([]) do |times, time_of_day|
dt = DateTime.strptime(time_of_day, "%I:%M%p")
time = Time.local( dt.year, dt.month,, dt.hour, dt.min )
time += ( 60 * 60 * 24 ) if times.last && times.last > time
# Compute the average time
average_time = times.inject(0) {|m,t| m + t.to_i } / times.size
# Format the average time"%I:%M%p").downcase.gsub(/^0/, '')
# Execute tests if this file is run by itself.
if $0 == __FILE__
require "test/unit"
include AverageTimeOfDay
class TestAverageTimeOfDay < Test::Unit::TestCase
def test_average_time_of_day
assert_equal "12:01am", average_time_of_day(
["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"] )
assert_equal "6:51am", average_time_of_day(
["6:41am", "6:51am", "7:01am"] )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment