Age Quiz

This is a follow-up to my first Ruby-related post. In that post, I mentioned potential additions to the code; I’ve since made those, and also cleaned it up a bit:

# Age Quiz
# agequiz.rb
# Asks user his name and when he was born. It then calculates
# the user's age, and offers different comments for kids, old
# people, and everyone else.
puts 'What is your name?'
name = gets.chomp
puts 'What year were you born in?'
year = gets.chomp
puts 'What month were you born in?'
month = gets.chomp
puts 'What day were you born on?'
day = gets.chomp
ageY = ((Time.new - Time.mktime(year,month,day))/31557600).to_i
puts 'Well, ' + name + ', you are ' + ageY.to_s + ' years old.'
if ageY < 18
puts 'Enjoy your youth while it lasts.'
elsif ageY >= 70
puts 'You\'re old. Get off the road.'
elsif
puts 'That means it\'s time to get a job!'
end

In the original code, it took four lines to get the age in years:

birthday = Time.mktime(year,month,day)
now = Time.new
ageSeconds = now - birthday
ageYears = ageSeconds/31557600

The “birthday,” “now,” and “ageSeconds” variables were completely unnecessary. They made it easier to work out exactly what was happening, but were wasteful. In the new version, it’s just:

ageY = ((Time.new - Time.mktime(year,month,day))/31557600).to_i

I can then use this variable in a series of if/elsif statements that returns different results for different ages. I think it’s funny.

The only thing that’s still a problem is that it accepts only numerical input for the date, and doesn’t have any built-in error handling. If someone types “March,” instead of “3,” it has no idea what to do. The easy solution would be to just tell people in the instructions to use numbers. To make it even easier for people, I could ask them to enter in their date of birth on a single line, using a provided format. Unfortunately, I don’t yet know how to extract such an entry as three separate numbers. This first app may get visited yet again.