Skip to content

Instantly share code, notes, and snippets.

@vikasmaskeri
Created October 9, 2009 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikasmaskeri/0f332e2531ab2fdbd991 to your computer and use it in GitHub Desktop.
Save vikasmaskeri/0f332e2531ab2fdbd991 to your computer and use it in GitHub Desktop.
def average_time_of_day(time_array)
hours= minutes = count= 0 # initialize
y=[] # initialize
time_array.each do |t|
t1 = t.split(':') # Parse the string to find the time
if (t1.last.end_with?('am') && (t1.first.to_i < 10)) # Count the total no. of am
count +=1
end
hours += t1.first.to_i # total hours
minutes += t1.last.chop.chop.to_i # total minutes
end
hours+= (minutes/60) + (12*count) # recalculating the no. of hours for the time in 'am'
minutes = minutes%60 # recalculating the no. of minutes after updating the no. of hours
total_time = hours*60 + minutes # total time in minutes
average_time = total_time/(time_array.length) # average time in minutes
average_hours = (average_time/60)%12 # average no. of hours
average_minutes = average_time%60 # average no. of minutes
part = average_hours < 10 ? "am" : "pm" # time of the day i.e. am or pm
puts "#{average_hours}:#{average_minutes}#{part}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment