Created
June 14, 2016 14:58
-
-
Save mkwardakov/25f76706abac66b311ae3c135bc9e698 to your computer and use it in GitHub Desktop.
3 approaches to time string parse and calculate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# regexp parser and eval variant | |
str = "1 year 2 months 3 days 2 hours 3 minutes 59 seconds" | |
t = {'minute[s]?': '*60+', 'hour[s]?': '*60*60+', 'day[s]?': '*60*60*24+', 'second[s]?': '+0', 'month[s]?': '*30*60*60*24+', 'year[s]?': '*12*30*60*60*24+'} | |
s = t.each {|x,y| str.gsub!(Regexp.new(x.to_s), y)} | |
seconds = eval(str) | |
# hash parser and inject variant | |
SECOND = SECONDS = 1 | |
MINUTE = MINUTES = 60 | |
HOUR = HOURS = 3600 | |
DAY = DAYS = 86400 | |
WEEK = WEEKS = 604800 | |
MONTH = MONTHS = 2419200 | |
YEAR = YEARS = 29030400 | |
def str_to_sec_with_const(str) | |
Hash[*str.strip.split(" ")].invert.inject(0){|result,(k,v)| result + Object.const_get(k.upcase) * v.to_i} | |
end | |
# RoR variant | |
"1 year 2 second 3 hours 17 days".scan(/(\d+)\s+(\w+)/).map{ |m| m[0].to_i.send(m[1]) }.sum.seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment