Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@leonardofaria leonardofaria commented Aug 4, 2016

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