Ruby Wizardry Read online




  Ruby Wizardry: An Introduction to Programming for Kids

  Eric Weinstein

  Published by No Starch Press

  To my teachers

  About the Author

  Eric Weinstein has helped millions of people learn to program through Codecademy, where he designed and authored the Ruby curriculum and contributed courses on Python, JavaScript, HTML/CSS, and PHP. He has also taught creative writing to undergraduates and veterans of the wars in Iraq and Afghanistan at New York University, where he was a Veterans Writing Workshop Fellow. He writes Ruby for a living in New York City.

  About the Technical Reviewers

  Peter Cooper is the editor of Ruby Weekly, a chair of O’Reilly’s Fluent web development conference, and the author of Beginning Ruby (Apress). He tweets at @peterc.

  Pat Shaughnessy is the author of Ruby Under a Microscope (No Starch Press) and also blogs at http://patshaughnessy.net/. A fluent Spanish speaker, Pat frequently visits his wife’s family in northern Spain. Pat lives outside of Boston with his wife and two children.

  Foreword

  A long time ago, I was a little kid growing up on a farm in rural Pennsylvania. My hometown is small enough that my parents’ farm was just half a mile down the road from my maternal grandparents’ house, my mother’s childhood home.

  One day, when I was seven years old, I was visiting my grandparents. It just so happened that one of my uncles also dropped by on that particular day. He wanted to give my grandparents a present: their first computer, a Mac Plus.

  You see, my uncle was heavily involved in all kinds of computing shenanigans. And computers were still a new thing in those days, so not many people had them. My grandparents, caring about their son and his interests, decided it would be a good idea to check out this whole “computer” thing.

  Excited by all the hubbub, my uncle called me over to the computer and explained what it was. He told me that you could do all kinds of things with computers, but that he thought I might like this one. On the screen appeared these immortal words:

  Welcome to ADVENTURE! Original development by Willie Crowther Major features added by Don Woods Conversion to BDS C by J. R. Jaeger Unix standardization by Jerry D. Pohl Conversion to PHP by Matt G. S. Cox Adapted for AMC.com by Rick Adams To play the game, type short phrases into the command line below. If you type the word "look," the game gives you a description of your surroundings. Typing "inventory" tells you what you're carrying. "Get" "drop" and "throw" helps you interact with objects. Part of the game is trying out different commands and seeing what happens. Type "help" at any time for game instructions. Would you like more instructions? no You are standing at the end of a road before a small brick building. Around you is a forest. A small stream flows out of the building and down a gully. What's next?

  Then, just a blinking cursor. By typing in simple instructions, I was able to explore a wonderful world, with an endless cave, a sneaky pirate, and a maze of twisty little passages, all alike. I was absolutely enthralled. My uncle told me, offhandedly, that some people called programmers had to actually teach the computer know how to play the game. I was hooked. I started asking to “go see Grandma” so much that my parents started saying, “You don’t want to see Grandma, you want to play with Grandma’s computer.”

  “No, I want to see Grandma and play with her computer,” I replied.

  Today, computers are very different. That Mac Plus had an 8 MHz processor, which could handle 1.4 million instructions per second. It also had 1MB of RAM. An iPhone 5s, today, has a 1.3 GHz processor, which can handle 18200 million instructions per second, and has 1GB of RAM. Games today don’t present you with some text; they present you with full 3D graphics.

  But I still firmly believe that a computer can change a child’s life.

  Ruby Wizardry is a book that captures that wonder I had as a child, sitting at this thing they called a “keyboard” for the first time. Ruby is a much nicer programming language than the GW-BASIC I cut my teeth on, but the core idea is the same. Give a child a way to bring their imagination to life, and amazing things will happen.

  I hope Ruby Wizardry brings you the same joy that computers have always brought me.

  Steve Klabnik

  Acknowledgments

  This book would not have been possible without the tireless efforts of dozens—possibly even dozens of dozens!—of people.

  First, my wife, Laura, who not only tolerated my all-night writing sessions and endless requests for feedback on story ideas, but also at various times pinch hit as literary agent, proofreader, sanity checker, and stop-reading-the-Internet-and-get-back-to-work!-er. This book would never have come to be without her love and support.

  My family, especially my father, who read to me almost every night for years, and my mother, who (for better or worse) taught me that I could do anything to which I stubbornly committed myself.

  My teachers, to whom this book is dedicated, particularly my teachers in the Ruby community: Cole Brown, Linda Liukas, and Dean Strelau, as well as all the brilliant, dedicated facilitators and students at Hacker School.

  Of course, Ruby Wizardry would not have been possible without Tyler Ortman, Riley Hoffman, Bill Pollock, and the amazing people at No Starch Press. I literally can’t thank them enough for their insight, energy, and dedication.

  Steve Klabnik, who read an early version of this book and wrote a wonderful foreword for it, as well as Peter Cooper and Pat Shaughnessy, who did the technical review and gave me much greater insight into the nitty-gritty of the Ruby language. All three are phenomenal teachers and Rubyists.

  why the lucky stiff, whose book why’s (Poignant) Guide to Ruby was one of the first Ruby books I read and who was the first to really show me the significance of and enthusiasm for art in the language and the community. I hope this book evokes some of the same feelings of excitement and wonder I felt when reading why’s work.

  Finally, Dave, who introduced me to Bill at No Starch Press and made this whole thing possible.

  Chapter 1. What This Book’s About

  You found this book! Okay, awesome. I was really hoping it would get to you.

  Imagine someone tells you he’s discovered a new way of writing. Not a new language, like French or Japanese or Elvish, but a whole new kind of writing that makes your stories actually happen. If you described a maze, people could enter—and get lost in—that maze. If you wrote about a faraway planet where robot pirates fought ninja wizards, that planet would totally exist. Not only that, but you could write dialogue like "Beep boop shiver me circuits" or cast spells like ninja_wizard.throw_flaming_ninja_stars. Crazy, right? And that’s probably exactly what you’d say: that this is completely crazy and whoever thought of it has too much time on his hands. Too much imagination.

  Well, it turns out there’s no such thing as too much imagination. So! Imagine me this: not only is this crazy new way of writing real, but you can learn how to do it. You could, with a little practice, figure out how to make your own worlds with your own rules. You’d be in charge, and you could do pretty much anything you could think of. Not only that, but if you got really good at it, people would come from all over to experience the worlds you built and use all the amazing things you created.

  You can stop imagining (for now, at least). I’m telling you that this is true! And this book can help you do it. The pages you now hold in your hands are a guide to a programming language called Ruby that will let you do all these things, and all you need is your brain, a computer, and Ruby.

  How can this be? you might be thinking. If something this cool and powerful existed, I definitely would have heard about it by now.

  Which brings us to our next topic.

  Why Learn Programming (and Why Ruby)?

  Le
arning to program sounded boring to me when I was younger. I thought programming and computers were all about math and logic—that there was no room to be creative or do anything interesting. All day long, people told me what to do: go to school, walk the dog, go to the dentist, do my homework. I figured programming would be more of the same, so I avoided it completely. Instead, I wrote stories about space travel, magic, and distant worlds where not only did amazing things happen, but I was in charge! I still write stories all the time, but even the best stories end when the reader turns the last page. As much as you want starships or ninja wizards to be real, writing stories about them doesn’t make that happen. So I did write a lot of stories, but I also had to go to the dentist.

  Then something very strange happened: I decided to give programming a try. I discovered that this thing I thought would be terribly dry and boring was exactly the opposite—it was challenging and fun. Suddenly, I was calling the shots! If I told the computer to make a puzzle game, it made a puzzle game. If I told it to make a website, it made a website. It made real things in the world that I could see, play with, and use. It was as if all the stories I had been writing for years could now come to life, and all it took was this little box and a language I could use to talk to it.

  It’s true that some programming languages are hard, and some are downright confusing. Ruby is different: it was designed to make you happy—to be easy for you to read and understand, not just the computer. Ruby was built to help you tell stories that computers and human beings can both enjoy, and so instead of weird symbols or words like static and void, you get programs that look almost like English, with words like unless, rescue, self, and even begin and end.

  Just as with any programming language, learning Ruby will help you learn important skills, make cool things, and feel accomplished. But mostly, you’ll just have fun. And among programming languages, I think Ruby is the most fun.

  Let’s say you wanted to program the computer to say “Howdy!” If you wanted to do this in another language—for instance, Java—you might have to write something really complicated, like this:

  class Howdy { public static void main (String[] args) { System.out.println("Howdy!"); } }

  That’s a lot of code to print one word. To do the same thing in Ruby, you just type:

  puts "Howdy!"

  That’s it! Ruby puts the word right there on the screen. Simple, right? Ruby is all about making you a happy and productive programmer (oh yeah—you’re a programmer now), so it gets rid of a lot of complicated syntax (like { and ;) and lets you avoid writing boring things like public static void main all over the place. And since Ruby can do pretty much all the stuff that trickier languages like Java can do, you’ll be able to build amazing things faster and with less effort.

  Let’s get started!

  All Adults on Deck: Installing Ruby

  All right—this is the part where you might want to grab your mom, dad, grandpa, grandma, aunt, uncle, teacher, or another local adult to help you install Ruby on your computer. Ruby is free, but you’ll need an Internet connection to download it if you don’t already have it.

  The directions are a little different depending on which kind of computer you have, so ask your adult if you’re not sure!

  If you’re running Windows, skip ahead to Installing on Windows.

  Installing on Mac or Linux

  First, let’s check to see if you already have Ruby installed. If you’re on a Mac or a computer running Linux, you can check to see which version of Ruby you have on the command line—this is where you’ll be typing your Ruby programs.

  The command line is probably very different from the way you usually use your computer (clicking icons and moving things with your mouse), but once you get used to it, the command line can be much faster and easier.

  On a Mac or Linux computer, your command line is in an application called Terminal. Find your Terminal application and open it. You should see something like this:

  Once you’ve got the Terminal open, go ahead and type the following line (you don’t need to type the dollar sign—just the ruby -v bit) and press ENTER:

  $ ruby -v

  If Ruby is installed, you’ll get back something like this:

  ruby 2.0.0p247

  If you get this response and it includes 2.0.0, you’re all set! Skip ahead to Achievement Unlocked: Ruby Installed!. If you get a number other than 2.0.0 (for instance, 1.9.3 or 1.8.7), we’ll need to get you on version 2.0.0 (the version this book uses). If your computer is super fancy, you might already be on Ruby 2.1—the code in this book should work in Ruby 2.1, too. For maximum awesomeness and minimal errors, you should run all the examples using Ruby 2.0.0.

  If your computer says something like this:

  -bash: ruby: command not found

  then you don’t have Ruby. No worries. Grab an adult and skip to Appendix A for detailed step-by-step instructions. We’ll install it there! Come back to this chapter when you’re done.

  Installing on Windows

  If you’re on a PC running Windows, you can check if Ruby is installed by opening the command prompt. We’ll be using Windows 7 in this example. You can open the command prompt from the Start menu or by searching for cmd.exe; once you find it, double-click it to open the application. You should see something like this:

  Your command prompt—the little bit before the >—will probably be different from mine, but that’s okay! Type ruby -v and then press ENTER:

  > ruby -v

  If you get a response that includes 2.0.0, you’re all set! If you see a Ruby version other than 2.0.0, or if you get this error:

  'ruby' is not recognized as an internal or external command, operable program or batch file.

  then we’ll need to go ahead and install Ruby. Let’s get to it!

  Using RubyInstaller

  The easiest way to install Ruby on Windows is to go to http://rubyinstaller.org/downloads/ and download Ruby 2.0.0-p481. (Don’t worry if the number after the p on the installation website is a little higher than what’s shown here; that just means that version is very slightly newer, but it’s still Ruby 2.0 and should work great.) Once the download is finished, go to the folder where you saved the .exe file and double-click it to run the installer. Here’s what it will ask you to do:

  When it prompts you for the language to use during installation, choose “English” (or whichever language you know best).

  The installer will ask you to accept its license agreement. Check “I accept the License” and then click Next.

  The installer will ask you where you’d like to install Ruby, defaulting to C:Ruby200. This is great! You’ll also see a checkbox that says “Add Ruby executables to your PATH.” Make sure that box is checked, then click Install.

  If all goes well, you should get a “Completing the Ruby Setup Wizard” screen. Click Finish, and you’re done!

  Once the installer runs, close your command prompt, reopen it, and enter ruby -v; you should see your computer print a response with ruby 2.0.0 in it. Mine looks like this (yours might be slightly different):

  ruby 2.0.0p481 (2014-05-08) [i386-mingw32]

  Achievement Unlocked: Ruby Installed!

  Perfect! Now that you’ve got Ruby installed, we can start learning our way around. In the next chapter, we’ll cover some Ruby basics and learn how to use Ruby interactively, meaning you’ll get to see Ruby run your code just by pressing the ENTER key. In the chapters that follow, you’ll learn the ins and outs of the Ruby language through a series of stories. Since Ruby programs are, after all, just stories you write for the computer to understand, and Ruby is all about writing code that’s nice for people and computers to read, I figure it only makes sense to use stories to show you how it all works. They’re pretty good stories, I think.

  You might be tempted to just read the code in this book and say to yourself, “Yup, this makes sense! I don’t need to run the code.” I thought that was true when I started programming, but boy, was I wrong. The only way t
o learn how to write code is, well, to write code, and you’re cheating yourself out of a lot of really cool knowledge if you only read these examples and never run a line of Ruby.

  One more word of advice before we set out on our adventure: you might have to read something more than once or run a piece of code a few times to really get it. That’s okay! Learning to program isn’t just a new way of writing—it’s a new way of thinking, too. It might be a little hard sometimes, but I promise that if you stick with it, you’ll get it. Believe me, there are people way less smart and enthusiastic than you who have learned how to program, and if they can do it, so can you.

  Putting on the Ruby Slippers

  Okay, so you’ve got your very own copy of Ruby, and you know that Ruby is a language you can use to tell computers to do anything you want. But you’re probably overflowing with questions: Where did Ruby come from? Who created it and why? What amazing things have been created with it? What good is Ruby? Well, question no more: I’ll give you all those answers (plus a few bonus ones).

  While computers were invented about a bajillion years ago (the first devices you’d recognize as computers were created in the 1940s), Ruby was cooked up relatively recently, in 1993. You might think that 1993 was a bajillion years ago, too, and in some ways, you’re right. The Internet only had about a hundred websites. Nobody had smartphones. In fact, most people’s phones were connected to their walls by wires. These were dark times.