kchoi kchoi - 1 month ago 10
Ruby Question

summing up string representation of year and month durations in ruby

I was wondering if there is a way to sum up multiple durations in string representations like

2 years 2 months
,
10 months
,
3 years
and output
6 years

Answer

You could do that as follows.

str = "2 years 4 months, 10 months, 3 years"

r = /
    (\d+)          # match one or more digits in capture group 1
    \s+            # match one or more whitespace chars
    \b             # match a word break
    (years|months) # match 'years' or 'months' in capture group 2
    \b             # match a word break
    /x             # free-spacing regex definition mode

a = str.scan r
  #=> [["2", "years"], ["4", "months"], ["10", "months"], ["3", "years"]]
h = a.each_with_object(Hash.new(0)) { |(n,period),h| h[period] += n.to_i }
  #=> {"years"=>5, "months"=>14}
y, m = h["months"].divmod(12)
  #=> [1, 2] 
h["years"]  += y
  #=> 6 
h["months"] = m
  #=> 2 
h #=> {"years"=>6, "months"=>2}