Skip to content

Instantly share code, notes, and snippets.

@leonardofaria
Created August 4, 2016 16:43
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 leonardofaria/ff25202097f25ebcd1aff8ad9c488b43 to your computer and use it in GitHub Desktop.
Save leonardofaria/ff25202097f25ebcd1aff8ad9c488b43 to your computer and use it in GitHub Desktop.
Time Calculation using Ruby
require_relative './time_calculation.rb'
distance = Time.new - Time.parse('2016-1-1')
puts TimeCalculation.humanize(distance)+"\r"
Date_of_birth = '1888-2-15'
3.times do
distance = Time.new - Time.parse(Date_of_birth)
puts TimeCalculation.humanize(distance, false)+"\r"
sleep 1
end
require 'time'
class TimeCalculation
def self.pluralize(count, noun)
if count != 0
count == 1 ? "#{count.to_i} #{noun}" : "#{count.to_i} #{noun}s"
end
end
def self.humanize(secs, short = true)
output = [
[60, :second],
[60, :minute],
[24, :hour],
[365, :day],
[100, :year]
].map do |count, name|
if secs > 0
secs, n = secs.divmod(count)
pluralize(n, name)
end
end
if short
output.compact.reverse[0]
else
output.compact.reverse.join(' ')
end
end
end
@leonardofaria
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment