L
Leslie Viljoen
Hi people!
See my nifty little class for converting a few time strings to
seconds. See how the last line of self.seconds reverses an array and
then adds up each part, multiplying the first with 1, the second with
60 and the third with 60*60. So 1:25:20 is a total of one hour, 25
minutes and 20 seconds - all converted to seconds.
Now look how I have to make a magical auto-incrementing counter
variable because inject doesn't provide the element index. Is there a
better way than this? Should I write an inject_with_index?
Les
# Seconder.seconds parses time formats and converts them to seconds,
# returning a string representation. It accepts:
#
# 10:25:05
# 17d (17 days)
# 10h (10 hours)
# 25m
# 5s
# 25:05
# 5
class Seconder
DURATIONS = {'s' => 1, 'm' => 60, 'h' => 60*60, 'd' => 60*60*24}
def self.count
@counter += 1
end
def self.seconds(string)
if string !~
/^\d+$|^\d{1,2}:\d{1,2}$|^\d{1,2}:\d{1,2}:\d{1,2}$|^\d+s$|^\d+h$|^\d+m$|^\d+d$/
return "Format incorrect, try 10:25:05 for hh:mm:ss or 10h for 10 hours"
end
lastChar = string[-1,1]
if DURATIONS.has_key?(lastChar) && string.length > 1
firstChars = string[0..-2]
return (firstChars.to_i * DURATIONS[lastChar]).to_s
end
@counter = 0
string.split(":").reverse.map{|part| part.to_i}.inject{|sum, part|
sum + part * 60 ** count}
end
end
See my nifty little class for converting a few time strings to
seconds. See how the last line of self.seconds reverses an array and
then adds up each part, multiplying the first with 1, the second with
60 and the third with 60*60. So 1:25:20 is a total of one hour, 25
minutes and 20 seconds - all converted to seconds.
Now look how I have to make a magical auto-incrementing counter
variable because inject doesn't provide the element index. Is there a
better way than this? Should I write an inject_with_index?
Les
# Seconder.seconds parses time formats and converts them to seconds,
# returning a string representation. It accepts:
#
# 10:25:05
# 17d (17 days)
# 10h (10 hours)
# 25m
# 5s
# 25:05
# 5
class Seconder
DURATIONS = {'s' => 1, 'm' => 60, 'h' => 60*60, 'd' => 60*60*24}
def self.count
@counter += 1
end
def self.seconds(string)
if string !~
/^\d+$|^\d{1,2}:\d{1,2}$|^\d{1,2}:\d{1,2}:\d{1,2}$|^\d+s$|^\d+h$|^\d+m$|^\d+d$/
return "Format incorrect, try 10:25:05 for hh:mm:ss or 10h for 10 hours"
end
lastChar = string[-1,1]
if DURATIONS.has_key?(lastChar) && string.length > 1
firstChars = string[0..-2]
return (firstChars.to_i * DURATIONS[lastChar]).to_s
end
@counter = 0
string.split(":").reverse.map{|part| part.to_i}.inject{|sum, part|
sum + part * 60 ** count}
end
end