What This Book’s About - Ruby Wizardry: An Introduction to Programming for Kids (2014)

Ruby Wizardry: An Introduction to Programming for Kids (2014)

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.

image with no caption

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)?

Learning 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:

image with no caption

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:

image with no caption

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:

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

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

3.    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.

4.    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]

image with no caption

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 to 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.

But in the ancient world of the mid-1990s, a man named Yukihiro Matsumoto (or just “Matz” to his friends) was busy trying to invent the future. He was frustrated by programming languages that were designed to make life easy for computers but were hard for people to understand, read, remember, and use. Why wasn’t there a language that was built to be easy for people to use, a language that was clear, simple—and even fun?

Matz realized that his ideal programming language didn’t exist, so he created it. “I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy,” Matz has said. “That is the primary purpose of the Ruby language.”[1] And that’s Ruby in a nutshell: a fun way for you to create games, websites, or anything you can imagine with just your brain and a computer. Matz has had such a positive influence on the language he created that Ruby programmers have a saying: “Matz is nice, so we are nice,” or MINSWAN. Remember MINSWAN when you’re learning Ruby and especially when you’re teaching it to others!

Which reminds me: there are a lot of amazing things you can create with Ruby. Over the last few years, Ruby has been used to build major websites like Twitter and Hulu, iPhone apps, and even NASA simulations. That’s right: you can use Ruby to explore space! People are using Ruby for more and more projects every day, and with all the cool new tools and ideas constantly coming from the Ruby community, your imagination’s really the only limit when it comes to building your own programs.

image with no caption

These programs are written in scripts. This means that instead of having to do a long and boring process called compiling, you can just write a quick Ruby program, run it, and presto!

Your website is up, your game is working, your starship is shooting lasers at a witch queen. But how do you run these Ruby scripts? For that, we’ll need to learn about the ruby command and a little program called IRB.

Getting to Know IRB

In Ruby, you can print something to the screen just by typing the puts command. Let’s say we want to print out “Ruby is awesome!” Let’s give it a try—first we have to open IRB, a program for exploring Ruby.

If you’re using Mac or Linux, open the terminal and type:

irb

You only need to type irb, not the dollar sign; the dollar sign is my way of showing you that you should type something in the terminal.

If you’re using Windows, you can run IRB from the Start menu.

Once you have IRB open, you should see something like this:

2.0.0p247 :001 >

That’s IRB’s prompt, which is IRB’s way of telling you it’s ready for you to type something. It might look a bit different to you depending on your Ruby version, but it should end with a >.

In this book, we’ll simplify that to look like this:

>> 

Whenever you see >>, we’ll be using IRB. If you type this after the >> (don’t forget the quotation marks—they’re very important!):

>> puts "Ruby is awesome!"

when you press ENTER, you should see Ruby print out:

Ruby is awesome!

=> nil

Excellent! We’ve written a simple program to print some text to the screen. You’ll also see Ruby say something about “nil.” Don’t worry about this just yet; I’ll explain that part in a little while. (If you can’t wait: basically, this is Ruby telling you that it’s all done printing and has nothing else to give you. You’ll learn all about nil in Chapter 7.) The cool thing is, you’ve just written your very first Ruby program!

IRB will continue to prompt you and wait for you to type things until you tell it to stop, which you can do at any time by typing exit (or just quitting your terminal program).

Using a Text Editor and the ruby Command

The other way of writing Ruby commands is as a script, which is just writing many lines and then running them all at once, instead of one at a time. To write a script, you’ll need a program called a text editor. (This is not something like Microsoft Word, which is a word processor; a word processor is great for writing stories or reports for school, but it’s terrible for writing programs.)

NOTE

You can download all the scripts that appear in this book at http://nostarch.com/rubywizardry/But if you’re learning to program and following along with the story, try typing things out instead of just copying and pasting! You’ll learn a lot more.

Mac

All Macs come with a text editor called TextEdit (you can find it in your Applications folder). It’s very simple to use and works great for writing Ruby programs. If you’re looking for something with a little more pizzazz, you can download a very nice free text editor called Sublime Text 2 from http://www.sublimetext.com/2 (you’ll need OS X 10.6 or later).

Linux

There are a number of good editors for Linux, but Gedit is one of my favorites. You can download it from https://wiki.gnome.org/Apps/Gedit. Sublime Text 2 is also a very good editor for Linux and is available at http://www.sublimetext.com/2.

Windows

As I just mentioned, Microsoft Word is not good for writing programs. Notepad++, on the other hand, is a great free text editor for Windows that you can get from http://notepad-plus-plus.org/download/v6.6.7.html. You can also use the Sublime Text 2 editor, available athttp://www.sublimetext.com/2.

Creating Your First Script

Once you’ve installed a text editor, open it and type the same thing you typed in IRB:

puts "Ruby is awesome!"

Go ahead and save this file as awesome.rb in any folder you’d like (it’s a good idea to create a ruby folder now to put all your Ruby programs in). Then, open your terminal and change into the folder where you saved awesome.rb. Here’s how to do that with the cd command:

§  On Mac or Linux, your prompt (the bit to the left of the $ on the command line) looks something like /Users/username $. If you saved awesome.rb in a folder called ruby in your home folder, you can get to that folder on the command line by entering:

§  $ cd /Users/username/ruby

Don’t type the $ part, just everything after it. Also, don’t literally type username; you should replace that with whatever you see in your prompt! (Mine is /Users/eweinstein/, but yours will be different.)

§  On Windows, your prompt (the bit to the left of the > on the command line) looks something like C:\Users\username. If you saved awesome.rb in a folder called ruby in your home folder, you can get to that folder on the command line by entering:

§  > cd C:\Users\username\ruby

Don’t type the > part, just everything after it. Also, don’t literally type username; you should replace that with whatever you see in your prompt.

Once you’re in the ruby folder, enter:

ruby awesome.rb

You should see Ruby print out:

Ruby is awesome!

And that’s you running your first Ruby script. Nice work!

When to Use IRB and When to Use a Text Editor

So if we type the same thing into IRB and into our script file, and we get the same output, what’s the difference between the two? Basically, IRB will let you try out only one line of code at a time; every time you press the ENTER key, IRB will read, or evaluate, the code you wrote and spit out an answer. It’s a great way to try things out and see if they work.

This means that every time you press ENTER, Ruby will interrupt you with the result of calculating each line, like this:

>> 2 + 5

=> 7

>> 24 * 10

=> 240

>> 'Hi ' + 'there!'

=> "Hi there!"

The code in bold is what you’ve typed; below it is the response you get from IRB when you press ENTER. We don’t always need all that noise! Sometimes we just want to know the final result of all our work. To do that, we can write this same code as a script. Just open your editor from earlier (for example, TextEdit if you’re on a Mac, Gedit if you’re using Linux, or Notepad++ for a PC running Windows) and type the following:

puts 2 + 5

puts 24 * 10

puts 'Hi ' + 'there!'

Then save the script as script_example.rb, or any name you like with a .rb at the end (but no spaces allowed!), use cd to switch into the directory where you saved the script, and finally run the script with the ruby command:

ruby script_example.rb

This way, we’ll just get the printed-out information we want, without having to type line by line:

7

240

Hi there!

Not only is this easier to read, but we can now run the script over and over with ruby script_example.rb and do our calculations without retyping all the commands each time. We can save our program forever, change it, and build on it later.

The Prompts Used in This Book

Throughout the book, we’ll alternate between using IRB for small bits of code and running scripts for longer ones. Whenever you see the IRB prompt, which looks like this:

>> 

that means you should be running the code using IRB; when you don’t see it, it means you should type the script in your text editor and run it using the ruby command. Here’s what an IRB example looks like:

>> 2 + 2

=> 4

Let’s take a moment to talk about what each piece of this code does. The >> bit says, “We’re in IRB, which is a program that understands Ruby commands.” Remember, you don’t want to type >>; this just lets you know we’re using IRB. The >> in the book represents the IRB prompt on your own computer.

The bold code that reads 2 + 2 is a command for you to enter—type these lines exactly, then press ENTER. When you see several bold lines at an IRB prompt, just type them one at a time, pressing ENTER after each line.

But the second line in this code begins with =>. This is what IRB spits back out in response after you press ENTER. (That means you don’t have to type these bits either.) If you get an error after typing a command instead of seeing the result shown in the book, make sure you’ve typed your Ruby commands exactly. Computers are very dumb: they do exactly what you say and not always what you want!

Other programs in the book are longer, so you’ll want to be able to change or improve them and fix mistakes. That means you’ll want to write them with a text editor. I’ll remind you of what to use for each example as we go. But remember, when you don’t see IRB’s >>, you’ll want to use a text editor.

Once we jump into the story, you’ll hear about Computing Contraptions. These are imaginary versions of computers just like yours, and whenever you see characters in the story running Ruby on a Computing Contraption, they’re really just giving IRB and Ruby a spin, so you can follow along yourself at home.

Finally, some of the scripts later in the book get pretty long. I’ll break those up into multiple sections and narrate each one. You’ll see numbered balls that look like this:

➊ ➋ ➌ ➍ ➎

I’ll refer to those numbers in the text so you can walk through each of the examples step-by-step. You don’t type these into the computer; they’re just for reference!

Again, don’t worry if you forget the differences between the IRB and Ruby script prompts—I’ll remind you as we go along!

Into the Shiny Red Yonder

Don’t worry about understanding all the code you just saw in these examples. We’ve only just started learning Ruby, and I promise we’ll go through all of its secrets over the course of the next few chapters. We’ll cover how to handle text and numbers, how to help our programs make decisions based on information they get from the people using them, how to create our own Ruby commands, how to write scripts that will connect to websites on the Internet, and much more.

I said earlier that writing Ruby is more like writing stories than writing instructions for a machine, so I’ll be using stories to teach you how Ruby works. In the pages that follow, I’ll introduce you to a few characters who will help explain everything you’d ever want to know about Ruby. Some will be expert Ruby programmers, and some, like you, will be brand new to the language. Many will have all sorts of problems that they think can’t be solved, but with a bit of hard work and some Ruby magic, they’ll find out that their troubles aren’t nearly as bad as they seem. Speaking of magic, there’ll be a bit of that, too—a king, a queen, a castle, an enchanted (possibly slightly haunted) forest, a wandering minstrel, some witches and wizards, a dragon or two, and a couple of kids a lot like you who have wandered into this crazy kingdom and have no choice but to explore . . .

image with no caption


[1] Google Tech Talks, Feb. 2008 (https://www.youtube.com/watch?v=oEkJvvGEtB4).