September 2008 Archives
I’ve been toying with the idea of learning a programming language for a while. Earlier today, I decided to find a good Cocoa tutorial. In the introduction to the one I found, it told me to try learning Ruby first, since I don't have any real prior experience with any programming. At any rate, I found myself reading "Learn to Program," by Chris Pine. I’m not even finished reading it and yet I’ve already made a functional Ruby app, from scratch. He shows different techniques, and gives examples, but at the end of each section, offers additional application ideas, that used the techniques you just learned. I decided to try one of them out. It asks your name and when you were born, then calculates your age and tells you to get a job.
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
birthday = Time.mktime(year,month,day)
now = Time.new
ageSeconds = now - birthday
ageYears = ageSeconds/31557600
puts 'Well, ' + name + ', you are ' + ageYears.to_i.to_s + ' years old.'
puts 'That means it\'s time to get a job!'
This results in (user input in italics):
What is your name?
Kirk
What year were you born in?
1984
What month were you born in?
3
What day were you born on?
13
Well, Kirk, you are 24 years old.
That means it's time to get a job!
Obviously it’s simple now, but I think it's a good start. I’ve also got ideas as to how to make it even more interesting. I could throw in some if/elsif statements and have it give different comments, depending on your age. Perhaps it would tell a 12-year-old to enjoy his youth while he had it, or implore an octogenarian to please stop driving.
In any case, I’m proud of it ... like stick-it-on-the-refrigerator proud, except that my blog will work as the fridge.