Skip to content

Instantly share code, notes, and snippets.

@blarosen95
Created May 31, 2018 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blarosen95/39248a925b724a059aab23504692fe4e to your computer and use it in GitHub Desktop.
Save blarosen95/39248a925b724a059aab23504692fe4e to your computer and use it in GitHub Desktop.
def format_duration(seconds)
*init, last = [3600 * 24 * 365, 3600 * 24, 3600, 60, 1]
.collect {|x| div, seconds = seconds.divmod(x); div}
.reverse
.zip([" second", " minute", " hour", " day", " year"])
.keep_if {|x, y| x != 0}
.map{|x, y| x.to_s + y + (x > 1 ? "s" : "")}
.reverse
last ? "#{init.join(", ")}#{init == [] ? "" : " and "}#{last}" : "now"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment