Pretty Printing Seconds in Ruby

I must have written various versions of this code 20 times so far in my career, but never so quickly and cleanly. I love ruby.

    min, sec = sec / 60, sec % 60
    hour, min = min / 60, min % 60
    day, hour = hour / 24, hour % 24
    week, day = day / 7, day % 7
 
    [
      week > 0 ? "#{week} weeks" : nil,
      day > 0 ? "#{day} days" : nil,
      hour > 0 ? "#{hour} hours" : nil,
      min > 0 ? "#{min} minutes" : nil,
      sec > 0 ? "#{sec} seconds" : nil
    ].compact.join(", ")

The really cool thing is the multiple assignment that ruby lets you do. I haven’t used it for something exactly like this before, but I do use it often and it’s really nice.

I feel like there should be a better way to do the bottom half of this, but this is pretty damn readable, I think. You might have to have a little rubyFU to remember what compact does – which is get rid of the nils.

Anyway, this was about 15 minutes of work (and I did it test first).

Tags:

Comments are closed.