The Care and Feeding of Your Baby Dragon

Learn to Program, Third Edition — by Chris Pine (71 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Methods: new vs. initialize | TOC | Progress Checkpoint 👉

You know how to create your own classes, even some of the subtle bits, but so far you’ve only seen a small, fluffy, toy example. Let me give you something a bit more interesting. Let’s say we want to make a simple virtual pet, a baby dragon.

Like most babies, it should be able to eat, sleep, and poop, which means you’ll need to be able to feed it, put it to bed, and take it on walks. Internally, your dragon will need to keep track of whether it’s hungry, tired, or needs to go out, but you won’t be able to see that when you interact with your dragon, the same way you can’t ask a human baby, “Are you hungry?” You’ll also add a few other fun ways you can interact with your baby dragon, and when your baby dragon is born, you’ll give it a name. (Whatever you pass into the new method is then passed onto the initialize method for you.)

Start by defining the class and the initialize method:

baby_dragon.rb

​ ​class​ Dragon
​ ​def​ ​initialize​(name)
​ @name = name
​ @asleep = ​false​
​ @stuff_in_belly = 10 ​# baby is full​
​ @stuff_in_intestine = 0 ​# baby doesn't need to go​

​ puts ​"​​#{​@name​}​​ is born."​
​ ​end​
​ ​end​

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.