Skip to content

Instantly share code, notes, and snippets.

@bsjohnson
Created November 9, 2015 13:46
Show Gist options
  • Save bsjohnson/cab2d61107a21dce0b50 to your computer and use it in GitHub Desktop.
Save bsjohnson/cab2d61107a21dce0b50 to your computer and use it in GitHub Desktop.
Girl DevelopIt - Birth Date calculations and printing
require "time"
puts "Enter your birthday:"
birthday = gets.chomp
puts "You entered: #{Time.parse(birthday)}\n"
birth_date = Time.parse(birthday) # Parse what we entered and store it in a variable
# Calculate the time difference between now and the birth date. This gives us the difference in SECONDS.
seconds_diff = Time.now - birth_date
# Let's figure out how many seconds are in a minute, hour, day, and year.
minute_seconds = 60
hour_seconds = 60 * minute_seconds # 60 minutes in an hour
day_seconds = 24 * hour_seconds # 24 hours in a day
year_seconds = 365 * day_seconds # 365 days in a year (don't worry about leap year.)
# Now, divide our age in seconds by each unit to figure out how old we are in those units.
years_old = seconds_diff / year_seconds
days_old = seconds_diff / day_seconds
hours_old = seconds_diff / hour_seconds
minutes_old = seconds_diff / minute_seconds
puts "Your age in: "
puts " Years: #{years_old}"
puts " Days: #{days_old}"
puts " Hours: #{hours_old}"
puts " Minutes: #{minutes_old}"
# Let's do this again using a hash
ages_hash = {
:years => years_old.round(2), # .round(x) lets you round a number to x number of decimal places
:days => days_old.round(2),
:hours => hours_old.round(2),
:minutes => minutes_old.round(2)
}
puts "\n" # Print a blank line.
puts "Your age again: (using a hash)"
ages_hash.each { |key, value| puts "\tYou are #{value} #{key} old." }
# Let's figure out how old we are right now.
age_years = years_old
# Divide our age in years by 365 to get days. The remainder is how many days it's been since our last birthday.
age_days = days_old % 365
age_hours = hours_old % 24
age_minutes = minutes_old % 60
age_seconds = seconds_diff % 60
# To drop the decimal numbers, just convert the number to an integer using .to_i
exact_age_sentence = "You are #{age_years.to_i} years, #{age_days.to_i} days"
exact_age_sentence = "#{exact_age_sentence}, #{age_hours.to_i} hours, #{age_minutes.to_i} minutes"
exact_age_sentence = "#{exact_age_sentence}, #{age_seconds.to_i} seconds old."
puts "\n#{exact_age_sentence}"
@kylekeesling
Copy link

It would be nice to put the date format in the puts prompt that asks for the user's birthday (line 6) - something like:

puts "Enter your birthday (YYYY-MM-DD):"

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