Skip to content

Instantly share code, notes, and snippets.

@davidbella
Created September 26, 2013 03:29
Show Gist options
  • Save davidbella/6709538 to your computer and use it in GitHub Desktop.
Save davidbella/6709538 to your computer and use it in GitHub Desktop.
Ruby: Exercise in converting different units of time
# Write a program that tells you the following:
#
# Hours in a year. How many hours are in a year?
# Minutes in a decade. How many minutes are in a decade?
# Your age in seconds. How many seconds old are you?
#
# Define at least the following methods to accomplish these tasks:
#
# seconds_in_minutes(1)
# minutes_in_hours(1)
# hours_in_days(1)
# days_in_weeks(1)
# weeks_in_years(1)
#
# Hours in a year. How many hours are in a year?
# Minutes in a decade. How many minutes are in a decade?
# Your age in seconds. How many seconds old are you?
#
# If I am 1,111 million seconds old, how old am I?
# Define an age_from_seconds method
def seconds_in_minutes(minutes)
minutes * 60
end
# minutes_in_hours(1)
def minutes_in_hours(hours)
hours * 60
end
# hours_in_days(1)
def hours_in_days(days)
days * 24
end
# days_in_weeks(1)
def days_in_weeks(weeks)
weeks * 7
end
# Added a days_in_years since this doesn't flow down nicely from days_in_weeks and weeks_in_years
def days_in_years(years)
years * 365
end
# weeks_in_years(1)
def weeks_in_years(years)
years * 52
end
# Added in years_in_decades - for fun
def years_in_decades(decades)
decades * 10
end
# Hours in a year. How many hours are in a year?
puts "Hours in a year: " + hours_in_days(days_in_years(1)).to_s
# Minutes in a decade. How many minutes are in a decade?
puts "Minutes in a decade: " + minutes_in_hours(hours_in_days(days_in_years(years_in_decades(1)))).to_s
# Your age in seconds. How many seconds old are you?
puts "My age (25 years) in seconds: " + seconds_in_minutes(minutes_in_hours(hours_in_days(days_in_years(25)))).to_s
#
# If I am 1,111 million seconds old, how old am I?
# Define an age_from_seconds method
def age_from_seconds(seconds)
years = seconds / 60 / 60 / 24 / 365
days = seconds / 60 / 60 / 24 % 365
hours = seconds / 60 / 60 % 24
minutes = seconds / 60 % 60
display_seconds = seconds % 60
puts "Years: #{years}"
puts "Days: #{days}"
puts "Hours: #{hours}"
puts "Minutes: #{minutes}"
puts "Seconds: #{display_seconds}"
end
age_from_seconds(1111000000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment