Skip to content

Instantly share code, notes, and snippets.

@whargrove
Created April 22, 2014 05:51
Show Gist options
  • Save whargrove/11166670 to your computer and use it in GitHub Desktop.
Save whargrove/11166670 to your computer and use it in GitHub Desktop.
Takes pairs of time and returns total seconds for the duration of pairs and a parsed version of the whole duration
require 'time'
class Io
def self.get_duration(array)
# only evaluate if there are an even number of items in the array
if array.length.even?
# iterate through each argument
i_ary = []
array.each do |arg|
# parse arg as seconds since unix epoch
i_ary << Time.parse(arg).to_i
end
diff_ary = []
i_ary.each_with_index do |s, i|
if i.even? && s != i_ary.last
diff = i_ary[i + 1] - s
diff_ary << diff
end
end
sum = diff_ary.inject(:+)
mm, ss = sum.divmod(60)
hh, mm = mm.divmod(60)
puts " >> %d hours, %d minutes and %d seconds" % [hh, mm, ss]
puts " >> " + sum.to_s + " seconds"
else
raise
end
end
end
puts "Enter times, e.g. 8:30 AM, 9:30 AM, etc..."
times = gets.chomp.split(',')
if times.length.odd?
puts "You must enter an even number of times as comma separated values. Please try again."
exit(false)
end
Io.get_duration(times)
exit(true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment