Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
require 'time'
def average_time_of_day(arrival_times)
# This sum value will be used to calculate the average.
sum = 0
# next_meridian is the next "am" or "pm" value in the arrival_times, naturally it would be empty for the first arrival_time
next_meridian = ""
# next_day is used to keep the total_time_in_secs block aware of
# whether after the first 'PM to AM' transition in the list of times, the following times are
# also the next day or not. This boolean can later be used to generalize this method further to account
# for an array of arrival times covering more than 2 days.
next_day = false
# This block gives us the sum which we can then divide by the length of the list to get the average
arrival_times.each do |x|
x.include?("am") ? (temp_meridian = "am") : (temp_meridian = "pm")
current_day = Time.parse(x).day
if ((temp_meridian == "am") && (next_meridian == "pm") )|| next_day == true
sum += Time.parse("#{current_day+1} "+ x).to_f
next_meridian = temp_meridian
next_day = true
else
sum += Time.parse(x).to_f
next_meridian = temp_meridian
end
end
# Calculate the actual average clock time
average_time_in_secs = sum / arrival_times.length
puts Time.at(average_time_in_secs).strftime("%I:%M%p")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.