Skip to content

Instantly share code, notes, and snippets.

@justinxreese
Created April 12, 2011 15:41
Show Gist options
  • Save justinxreese/915751 to your computer and use it in GitHub Desktop.
Save justinxreese/915751 to your computer and use it in GitHub Desktop.
Convert time to a float
# If you come across the need to store time as a float in ruby (I won’t judge you),
# you can use this bit of code. It assumes that each subpart of the time string is
# 60 parts of the previous part. This works for hours, minutes and seconds,
# regardless of how it is entered, and will always use the first "part" as the base
# measurement, i.e. 12:30 minutes becomes 12.5 minutes
j = 0
timer = 0
"12:40:30".split(':').each do |y|
timer += y.to_f / (60**j); j += 1;
end
# In this example, the numbers 12, 0.66, and 0.008 are summed to give 12.6724 hours.
@ostapische
Copy link

ruby have method http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-each_with_index
and you can use it like this: "12:40:30".split(':').each_with_index do |y, j|

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment