Skip to content

Instantly share code, notes, and snippets.

@lisa
Created October 11, 2009 02:35
Show Gist options
  • Save lisa/207353 to your computer and use it in GitHub Desktop.
Save lisa/207353 to your computer and use it in GitHub Desktop.
# For http://rubylearning.com/blog/2009/10/08/rpcfn-average-arrival-time-for-a-flight-2/
# I take the lazy approach and assume 12:01am is today, not tomorrow.
def average_time_of_day(ary)
sec = ary.map do |t|
hour, min_with_noonside = t.split(":")
(hour.to_i * (min_with_noonside.include?("pm") ? 2 : 1) * 3600) + (min_with_noonside.to_i * 60)
end.inject(0) { |s,c| s += c } / ary.size
hour = sec / 3600
min = ((sec - hour * 3600) / 60).to_s
min += hour > 12 ? "pm" : "am"
hour -= 12 if hour > 12
"#{hour}:#{min}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment