Ruby PDF
Ruby PDF
LEARN RUBY
THE HARD WAY
Third Edition
“Shaw_FM” — 2014/11/8 — 17:24 — page 2 — #2
“Shaw_FM” — 2014/11/8 — 17:24 — page 3 — #3
LEARN RUBY
THE HARD WAY
A Simple and Idiomatic Introduction
to the Imaginative World of
Computational Thinking with Code
Third Edition
Zed A. Shaw
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark
claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied
warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental
or consequential damages in connection with or arising out of the use of the information or programs
contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities (which may include
electronic versions; custom cover designs; and content particular to your business, training goals, marketing
focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or
(800) 382-3419.
For questions about sales outside the United States, please contact international@pearsoned.com.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval
system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or
likewise. To obtain permission to use material from this work, please submit a written request to Pearson
Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may
fax your request to (201) 236-3290.
ISBN-13: 978-0-321-88499-2
ISBN-10: 0-321-88499-X
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing, December 2014
“Shaw_FM” — 2014/11/8 — 17:24 — page v — #5
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
The Hard Way Is Easier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Reading and Writing . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Attention to Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Spotting Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Do Not Copy-Paste . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Using the Included Videos . . . . . . . . . . . . . . . . . . . . . . . . 3
A Note on Practice and Persistence . . . . . . . . . . . . . . . . . . . 3
A Warning for the Smarties . . . . . . . . . . . . . . . . . . . . . . . 4
Exercise 0 The Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
OS X: What You Should See . . . . . . . . . . . . . . . . . . . . . 7
Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Windows: What You Should See . . . . . . . . . . . . . . . . . . . 8
Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Linux: What You Should See . . . . . . . . . . . . . . . . . . . . . 9
Finding Things on the Internet . . . . . . . . . . . . . . . . . . . . . 10
Warnings for Beginners . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Exercise 1 A Good First Program . . . . . . . . . . . . . . . . . . . . . . 12
What You Should See . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Study Drills . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Common Student Questions . . . . . . . . . . . . . . . . . . . . . . . 17
Exercise 2 Comments and Pound Characters . . . . . . . . . . . . . . . 18
What You Should See . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Study Drills . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Common Student Questions . . . . . . . . . . . . . . . . . . . . . . . 19
Exercise 3 Numbers and Math . . . . . . . . . . . . . . . . . . . . . . . 20
What You Should See . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Study Drills . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Common Student Questions . . . . . . . . . . . . . . . . . . . . . . . 22
“Shaw_FM” — 2014/11/8 — 17:24 — page vi — #6
vi CONTENTS
CONTENTS vii
viii CONTENTS
CONTENTS ix
x CONTENTS
CONTENTS xi
xii CONTENTS
CONTENTS xiii
xiv CONTENTS
CONTENTS xv
Preface
T his simple book is meant to get you started in programming. The title says it’s the hard way to
learn to write code, but it’s actually not. It’s only the ”hard” way because it uses a technique
called instruction. Instruction is where I tell you to do a sequence of controlled exercises designed
to build a skill through repetition. This technique works very well with beginners, who know noth-
ing and need to acquire basic skills before they can understand more complex topics. It’s used in
everything from martial arts to music, to even basic math and reading skills.
This book instructs you in Ruby by slowly building and establishing skills through techniques like
practice and memorization, then applying them to increasingly dif cult problems. By the end of
the book you will have the tools needed to begin learning more complex programming topics. I
like to tell people that my book gives you your ”programming black belt.” What this means is that
you know the basics well enough to now start learning programming.
If you work hard, take your time, and build these skills, you will learn to code.
Acknowledgments
I would like to thank Angela for helping me with the rst two versions of this book. Without her,
I probably wouldn’t have bothered to nish it at all. She did the copyediting of the rst draft, and
supported me immensely while I wrote it.
I also want to thank Rob Sobers for suggesting I make a Ruby version of my Python book and doing
the initial work helping me convert it to use Ruby.
I’d also like to thank Greg Newman for doing the original cover art, Brian Shumate for early website
designs, and all of the people who read this book and took the time to send me feedback and
corrections.
Thank you.
“Shaw_Ex00” — 2014/11/7 — 18:41 — page 2 — #1
W ith the help of this book, you will do the incredibly simple things that all programmers do
to learn a programming language:
3. Make it run.
That’s it. This will be very dif cult at rst, but stick with it. If you go through this book, and do each
exercise for one or two hours a night, you will have a good foundation for moving onto another
book about Ruby to continue your studies. This book won’t turn you into a programmer overnight,
but it will get you started on the path to learning how to code.
This book’s job is to teach you the three most essential skills that a beginning programmer needs
to know: reading and writing, attention to detail, and spotting differences.
Typing the code samples and getting them to run will help you learn the names of the symbols,
get familiar with typing them, and get you reading the language.
Attention to Detail
The one skill that separates bad programmers from good programmers is attention to detail. In
fact, it’s what separates the good from the bad in any profession. You must pay attention to the
tiniest details of your work or you will miss important elements of what you create. In program-
ming, this is how you end up with bugs and dif cult-to-use systems.
By going through this book, and copying each example exactly, you will be training your brain to
focus on the details of what you are doing, as you are doing it.
“Shaw_Ex00” — 2014/11/7 — 18:41 — page 3 — #2
Spotting Differences
A very important skill (that most programmers develop over time) is the ability to visually notice
differences between things. An experienced programmer can take two pieces of code that are
slightly different and immediately start pointing out the differences. Programmers have invented
tools to make this even easier, but we won’t be using any of these. You rst have to train your
brain the hard way; then use the tools.
While you do these exercises, typing each one in, you will be making mistakes. It’s inevitable; even
seasoned programmers would make a few. Your job is to compare what you have written to what’s
required, and x all the differences. By doing so, you will train yourself to notice mistakes, bugs,
and other problems.
Do Not Copy-Paste
You must type each of these exercises in, manually. If you copy and paste, you might as well not
even do them. The point of these exercises is to train your hands, your brain, and your mind in how
to read, write, and see code. If you copy-paste, you are cheating yourself out of the effectiveness
of the lessons.
Between the time that I wrote Learn Python the Hard Way and Learn Ruby the Hard Way, I dis-
covered drawing and painting. I fell in love with making visual art at the age of 39; and I have
been spending every day studying it in much the same way that I studied guitar, music, and pro-
gramming. I collected books of instructional material, did what the books said, painted every
day, and focused on enjoying the process of learning. I am by no means an ”artist,” or even
that good, but I can now say that I can draw and paint. The same method I’m teaching you in
this book applied to my adventures in art. If you break the problem down into small exercises
and lessons, and do them every day, you can learn to do almost anything. If you focus on slowly
improving and enjoying the learning process, then you will bene t no matter how good you
are at it.
As you study this book, and continue with programming, remember that anything worth doing
is dif cult at rst. Maybe you are the kind of person who is afraid of failure, so you give up at
the rst sign of dif culty. Maybe you never learned self-discipline, so you can’t do anything that’s
”boring.” Maybe you were told that you are ”gifted,” so you never attempt anything that might
make you seem stupid or not a prodigy. Maybe you are competitive and unfairly compare yourself
to someone like me who’s been programming for more than 20 years.
Whatever your reason for wanting to quit, keep at it. Force yourself. If you run into a Study Drill
you can’t do, or a lesson you just do not understand, then skip it and come back to it later. Just keep
going, because with programming there’s this very odd thing that happens. At rst, you will not
understand anything. It’ll be weird, just like with learning any human language. You will struggle
with words, and not know what symbols are what, and it’ll all be very confusing. Then one day
BANG—your brain will snap and you will suddenly ”get it.” If you keep doing the exercises and
keep trying to understand them, you will get it. You might not be a master coder, but you will at
least understand how programming works.
If you give up, you won’t ever reach this point. You will hit the rst confusing thing (which is
everything at rst) and then stop. If you keep trying—keep typing it in, trying to understand it
and reading about it—you will eventually get it. If you go through this whole book, and you still
do not understand how to code, at least you gave it a shot. You can say you tried your best and a
little more and it didn’t work out, but at least you tried. You can be proud of that.
If you are reading this book and ipping out at every third sentence because you feel I’m insulting
your intelligence, then I have three points of advice for you:
1. Stop reading my book. I didn’t write it for you. I wrote it for people who don’t already
know everything.
2. Empty before you ll. You will have a hard time learning from someone with more knowl-
edge if you already know everything.
3. Go learn Lisp. I hear people who know everything really like Lisp.
For everyone else who’s here to learn, just read everything as if I’m smiling and I have a mis-
chievous little twinkle in my eye.
“Shaw_Ex01” — 2014/11/7 — 14:08 — page 12 — #1
12
EXERCISE 1
Y ou should have spent a good amount of time in Exercise 0 learning how to install a text editor,
run the text editor, run Terminal, and work with both of them. If you haven’t done that, then
do not go on. You will not have a good time. This is the only time I’ll start an exercise with a
warning that you should not skip or get ahead of yourself.
Type the following text into a single le named ex1.rb. Ruby works best with les ending in .rb.
ex1.rb
If you are on Mac OS X, then this is what your text editor might look like if you use TextWrangler:
“Shaw_Ex01” — 2014/11/7 — 14:08 — page 13 — #2
If you are on Windows using Notepad++, then this is what it would look like:
Don’t worry if your editor doesn’t look exactly the same, it should be close though. When you
create this le, keep in mind these points:
1. I did not type the line numbers on the left. Those are printed in the book so I can talk
about speci c lines by saying, ”See line 5.” You do not type line numbers into Ruby
scripts.
2. I have the puts at the beginning of the line and it looks exactly the same as what I have
in ex1.rb. Exactly means exactly, not kind of sort of the same. Every single character has
to match for it to work. Color doesn’t matter, only the characters you type.
ruby ex1.rb
If you did it right, then you should see the same output as in the What You Should See section of
this exercise. If not, you have done something wrong. No, the computer is not wrong.
“Shaw_Ex01” — 2014/11/7 — 14:08 — page 14 — #3
You may see different names before the ruby ex1.rb command, but the important part is that
you type the command and see the output is the same as mine.
“Shaw_Ex01” — 2014/11/7 — 14:08 — page 16 — #5
It’s important that you can read these error messages, because you will be making many of these
mistakes. Even I make many of these mistakes. Let’s look at this line by line.
2. Ruby tells us that the le ex1.rb has an error on line 3. The type of error is ”syntax error,”
and then some programmer jargon you can usually ignore.
WARNING! If you are from another country, and you get errors about ASCII encodings,
then put this at the top of your Ruby scripts:
It will x them so that you can use Unicode UTF-8 in your scripts without a problem.
Study Drills
The Study Drills contain things you should try to do. If you can’t, skip it and come back later.
3. Put a # (octothorpe) character at the beginning of a line. What did it do? Try to nd out
what this character does.
From now on, I won’t explain how each exercise works unless an exercise is different.
18
EXERCISE 2
C omments are very important in your programs. They are used to tell you what something does
in English, and they are used to disable parts of your program if you need to remove them
temporarily. Here’s how you use comments in Ruby:
ex2.rb
From now on, I’m going to write code like this. It is important for you to understand that every-
thing does not have to be literal. Your screen and program may visually look different, but what’s
important is the text you type into the le you’re writing in your text editor. In fact, I could work
with any text editor and the results would be the same.
$ ruby ex2.rb
I could have code like this.
This will run.
Again, I’m not going to show you screenshots of all the Terminals possible. You should understand
that the above is not a literal translation of what your output should look like visually, but the text
between the rst $ ruby ... and last $ lines will be what you focus on.
Study Drills
1. Find out if you were right about what the # character does and make sure you know what
it’s called (octothorpe or pound character).
2. Take your ex2.rb le and review each line going backward. Start at the last line, and
check each word in reverse against what you should have typed.
“Shaw_Ex02” — 2014/11/7 — 14:10 — page 19 — #2
4. Read what you typed out loud, including saying each character by its name. Did you nd
more mistakes? Fix them.
If # is for comments, then how come # -*- coding: utf-8 -*- works?
Ruby still ignores that as code, but it’s used as a kind of ”hack” or workaround for problems with
setting and detecting the format of a le. You will also nd a similar kind of comment for editor
settings.
249
APPENDIX
T his appendix is a quick, super-fast course in using the command line. It is intended to be done
rapidly in about a day or two, and is not meant to teach you advanced shell usage.
Sorry to be mean, but that’s what you have to do. If you have an irrational fear of the command
line, the only way to conquer an irrational fear is to just shut up and ght through it.
You are not going to destroy your computer. You are not going to be thrown into some jail at the
bottom of Microsoft’s Redmond campus. Your friends won’t laugh at you for being a nerd. Simply
ignore any stupid weird reasons you have for fearing the command line.
Why? Because if you want to learn to code, then you must learn this. Programming languages
are advanced ways to control your computer with language. The command line is the little baby
brother of programming languages. Learning the command line teaches you to control the com-
puter using language. Once you get past that, you can then move on to writing code and feeling
like you actually own the hunk of metal you just bought.
• Start at the beginning of the appendix and do each exercise exactly as you’re told.
• When you read something that doesn’t make sense or that you don’t understand, write
it down in your notebook. Leave a little space so you can write an answer.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 250 — #2
• After you nish an exercise, go back through your notebook and review the questions
you have. Try to answer them by searching online and asking friends who might know
the answer. Email me at help@learncodethehardway.org and I’ll help you, too.
Just keep going through this process of doing an exercise, writing down questions you have, then
going back through and answering the questions you can. By the time you’re done, you’ll actually
know a lot more than you think about using the command line.
• Tell yourself you will do it. Don’t try to nd tricks or easy ways out of it, just sit down and
do it.
• Write what you want to memorize on some index cards. Put one half of what you need
to learn on one side, then the other half on the other side.
• Every day for about 15–30 minutes, drill yourself on the index cards, trying to recall each
one. Put any cards you don’t get right into a different pile, just drill those cards until you
get bored, and then try the whole deck and see if you improve.
• Before you go to bed, drill just the cards you got wrong for about 5 minutes, then go to
sleep.
There are other techniques, like you can write what you need to learn on a sheet of paper, laminate
it, then stick it to the wall of your shower. While you’re bathing, drill the knowledge without
looking, and when you get stuck glance at it to refresh your memory.
If you do this every day, you should be able to memorize most of the things I tell you to memorize in
about a week to a month. Once you do, nearly everything else becomes easier and intuitive, which
is the purpose of memorization. It’s not to teach you abstract concepts, but rather to ingrain the
basics so that they are intuitive and you don’t have to think about them. Once you’ve memorized
these basics, they stop being speed bumps preventing you from learning more advanced abstract
concepts.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 251 — #3
The Setup
In this appendix you will be instructed to do three things:
For this rst exercise, you’ll be expected to get your Terminal open and working so that you can
do the rest of the appendix.
Do This
Get your Terminal, shell, or PowerShell working so you can access it quickly and know that it
works.
Mac OS X
For Mac OS X you’ll need to do this:
• In the top right corner, the blue ”search bar” will pop up.
• Type: terminal
• Click on the Terminal application that looks kind of like a black box.
• You can now go to your dock and CTRL-click to pull up the menu, then select
Options->Keep In dock.
Now you have your Terminal open and it’s in your dock so you can get to it.
Linux
I’m assuming that if you have Linux, then you already know how to get at your Terminal. Look
through the menu for your window manager for anything named ”Shell” or ”Terminal.”
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 252 — #4
Windows
On Windows, we’re going to use PowerShell. People used to work with a program called cmd.exe,
but it’s not nearly as usable as PowerShell. If you have Windows 7 or later, do this:
• Click Start.
• Hit Enter.
If you don’t have Windows 7, you should seriously consider upgrading. If you still insist on not
upgrading then you can try installing it from Microsoft’s download center. Search online to nd
”powershell downloads” for your version of Windows. You are on your own, though, since I don’t
have Windows XP, but hopefully the PowerShell experience is the same.
WARNING! If you have that really smart friend who already knows Linux, ignore him
when he tells you to use something other than bash. I’m teaching you bash. That’s it.
He will claim that zsh will give you 30 more IQ points and win you millions in the stock
market. Ignore him. Your goal is to get capable enough and at this level it doesn’t
matter which shell you use. The next warning is stay off IRC or other places where
”hackers” hang out. They think it’s funny to hand you commands that can destroy
your computer. The command rm -rf / is a classic that you must never type. Just
avoid them. If you need help, make sure you get it from someone you trust and not
from random idiots on the Internet.
Do More
This exercise has a large ”do more” part. The other exercises are not as involved as this one, but
I’m having you prime your brain for the rest of the appendix by doing some memorization. Just
trust me: this will make things silky smooth later on.
Linux/Mac OS X
Take this list of commands and create index cards with the names on the left on one side, and
the de nitions on the other side. Drill them every day while continuing with the lessons in this
appendix.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 253 — #5
cd change directory
ls list directory
cp copy a le or directory
mv move a le or directory
nd nd les
Windows
If you’re using Windows, then here’s your list of commands:
cd change directory
ls list directory
cp copy a le or directory
mv move a le or directory
dir -r nd les
Drill, drill, drill! Drill until you can say these phrases right away when you see that word. Then drill
the inverse, so that you read the phrase and know which command will do that. You’re building
your vocabulary by doing this, but don’t spend so much time you go nuts and get bored.
Do This
I’m going to teach you how to read these ”sessions” that I show you. You don’t have to type
everything I list here, just some of the parts:
• You do not type in the $ (UNIX) or > (Windows). That’s just me showing you my session
so you can see what I got.
• You type in the stuff after $ or >, then hit Enter. So if I have $ pwd, you type just pwd
and hit Enter.
• You can then see what I have for output followed by another $ or > prompt. That content
is the output and you should see the same output.
Let’s do a simple rst command so you can get the hang of this:
Linux/OS X
Exercise 2 Session
$ pwd
/Users/zedshaw
$
Windows
Exercise 2 Windows Session
PS C:\Users\zed> pwd
Path
----
C:\Users\zed
PS C:\Users\zed>
WARNING! In this appendix I need to save space so that you can focus on the important
details of the commands. To do this, I’m going to strip out the rst part of the prompt
(the PS C:\Users\zed above) and leave just the little > part. This means your prompt
won’t look exactly the same, but don’t worry about that.
Remember that from now on I’ll include only the > to tell you that’s the prompt.
I’m doing the same thing for the UNIX prompts, but UNIX prompts are so varied that
most people get used to $ meaning ”just the prompt.”
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 256 — #8
• There’s a prompt.
• It printed something.
• Repeat.
You just learned what pwd does, which means ”print working directory.” What’s a directory?
It’s a folder. Folder and directory are the same thing, and they’re used interchangeably. When
you open your le browser on your computer to graphically nd les, you are walking through
folders. Those folders are the exact same things as these ”directories” we’re going to
work with.
Do More
• Type pwd 20 times and each time say ”print working directory.”
• Write down the path that this command gives you. Find it with your graphical le browser
of choice.
• No, seriously, type it 20 times and say it out loud. Sssh. Just do it.
Whenever you get lost, it is most likely because you were typing commands and have no idea
where you’ve ended up. What you should do is type pwd to print your current directory. This tells
you where you are.
The next thing you need is a way of getting back to where you are safe, your home. To do this,
type cd ~ and you are back in your home.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 257 — #9
This means if you get lost at any time, you should type:
pwd
cd ~
The rst command pwd tells you where you are. The second command cd ~ takes you home so
you can try again.
Do This
Right now gure out where you are, and then go home using pwd and cd ~. This will ensure that
you are always in the right place.
Do This
Remember! You need to go home rst! Do your pwd and then cd ~ before doing this exercise.
Before you do all exercises in this appendix, always go home rst!
Linux/OS X
Exercise 4 Session
$ pwd
$ cd ~
$ mkdir temp
$ mkdir temp/stuff
$ mkdir temp/stuff/things
$ mkdir -p temp/stuff/things/frank/joe/alex/john
$
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 258 — #10
Windows
Exercise 4 Windows Session
> pwd
> cd ~
> mkdir temp
Directory: C:\Users\zed
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp\stuff
Directory: C:\Users\zed\temp\stuff\things\frank\joe\alex
>
This is the only time I’ll list the pwd and cd ~ commands. They are expected in the exercises every
time. Do them all the time.
What does it mean to make a directory? You might call directories ”folders.” They’re the same
thing. All you did in this exercise is create directories inside directories inside of more directories.
This is called a ”path” and it’s a way of saying ” rst temp, then stuff, then things, and that’s where
I want it.” It’s a set of directions to the computer of where you want to put something in the tree
of folders (directories) that make up your computer’s hard disk.
WARNING! In this appendix I’m using the / (slash) character for all paths since it works
the same on all computers now. However, Windows users need to know that you can
also use the \ (backslash) character and other Windows users will expect that at times.
Do More
• The concept of a ”path” might confuse you at this point. Don’t worry. We’ll do a lot more
with them and then you’ll get it.
• Make 20 other directories inside the temp directory in various levels. Go look at them
with a graphical le browser.
• Make a directory with a space in the name by putting quotes around it: mkdir "I Have
Fun"
• If the temp directory already exists, then you’ll get an error. Use cd to change to a work
directory that you can control and try it there. On Windows, Desktop is a good place.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 260 — #12
Do This
I’m going to give you the instructions for these sessions one more time:
• You type in the stuff after this, then hit Enter. If I have $ cd temp you just type cd temp
and hit Enter.
• The output comes after you hit Enter, followed by another $ or > prompt.
• Always go home rst! Do pwd and then cd ~ so you go back to your starting point.
Linux/OS X
Exercise 5 Session
$ cd temp
$ pwd
~/temp
$ cd stuff
$ pwd
~/temp/stuff
$ cd things
$ pwd
~/temp/stuff/things
$ cd frank/
$ pwd
~/temp/stuff/things/frank
$ cd joe/
$ pwd
~/temp/stuff/things/frank/joe
$ cd alex/
$ pwd
~/temp/stuff/things/frank/joe/alex
$ cd john/
$ pwd
~/temp/stuff/things/frank/joe/alex/john
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 261 — #13
$ cd ..
$ cd ..
$ pwd
~/temp/stuff/things/frank/joe
$ cd ..
$ cd ..
$ pwd
~/temp/stuff/things
$ cd ../../..
$ pwd
~/
$ cd temp/stuff/things/frank/joe/alex/john
$ pwd
~/temp/stuff/things/frank/joe/alex/john
$ cd ../../../../../../../
$ pwd
~/
$
Windows
Exercise 5 Windows Session
> cd temp
> pwd
Path
----
C:\Users\zed\temp
> cd stuff
> pwd
Path
----
C:\Users\zed\temp\stuff
> cd things
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 262 — #14
> pwd
Path
----
C:\Users\zed\temp\stuff\things
> cd frank
> pwd
Path
----
C:\Users\zed\temp\stuff\things\frank
> cd joe
> pwd
Path
----
C:\Users\zed\temp\stuff\things\frank\joe
> cd alex
> pwd
Path
----
C:\Users\zed\temp\stuff\things\frank\joe\alex
> cd john
> pwd
Path
----
C:\Users\zed\temp\stuff\things\frank\joe\alex\john
> cd ..
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 263 — #15
> cd ..
> cd ..
> pwd
Path
----
C:\Users\zed\temp\stuff\things\frank
> cd ../..
> pwd
Path
----
C:\Users\zed\temp\stuff
> cd ..
> cd ..
> cd temp/stuff/things/frank/joe/alex/john
> cd ../../../../../../../
> pwd
Path
----
C:\Users\zed
>
You should also see how I use the .. to move ”up” in the tree and path.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 264 — #16
Do More
A very important part of learning to use the command line interface (CLI) on a computer with
a graphical user interface (GUI) is guring out how they work together. When I started using
computers, there was no ”GUI” and you did everything with the DOS prompt (the CLI). Later,
when computers became powerful enough that everyone could have graphics, it was simple for
me to match CLI directories with GUI windows and folders.
Most people today, however, have no comprehension of the CLI, paths, and directories. In fact,
it’s very dif cult to teach it to them and the only way to learn about the connection is for you to
constantly work with the CLI until one day it clicks that things you do in the GUI will show up in
the CLI.
The way you do this is by spending some time nding directories with your GUI le browser, then
going to them with your CLI. This is what you’ll do next.
• cd back to temp with one command, but not further above that.
• cd to your Documents directory, then nd it with your GUI le browser (e.g., Finder,
Windows Explorer, etc.).
• Remember when you put quotes around a directory with spaces in it? You can do that
with any command. For example, if you have a directory I Have Fun, then you can do:
cd "I Have Fun"
Do This
Before you start, make sure you cd back to the directory above temp. If you have no idea where
you are, use pwd to gure it out and then move there.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 265 — #17
Linux/OS X
Exercise 6 Session
$ cd temp
$ ls
stuff
$ cd stuff
$ ls
things
$ cd things
$ ls
frank
$ cd frank
$ ls
joe
$ cd joe
$ ls
alex
$ cd alex
$ ls
$ cd john
$ ls
$ cd ..
$ ls
john
$ cd ../../../
$ ls
frank
$ cd ../../
$ ls
stuff
$
Windows
Exercise 6 Windows Session
> cd temp
> ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 266 — #18
Directory: C:\Users\zed\temp
> cd stuff
> ls
Directory: C:\Users\zed\temp\stuff
> cd things
> ls
Directory: C:\Users\zed\temp\stuff\things
> cd frank
> ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 267 — #19
Directory: C:\Users\zed\temp\stuff\things\frank
> cd joe
> ls
Directory: C:\Users\zed\temp\stuff\things\frank\joe
> cd alex
> ls
Directory: C:\Users\zed\temp\stuff\things\frank\joe\alex
> cd john
> ls
> cd ..
> ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 268 — #20
Directory: C:\Users\zed\temp\stuff\things\frank\joe\alex
> cd ..
> ls
Directory: C:\Users\zed\temp\stuff\things\frank\joe
> cd ../../..
> ls
Directory: C:\Users\zed\temp\stuff
> cd ..
> ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 269 — #21
Directory: C:\Users\zed\temp
>
There are a lot of options for the ls command, but you’ll learn how to get help on those later
when we cover the help command.
Do More
• Type every one of these commands in! You have to actually type these to learn them. Just
reading them is not good enough. I’ll stop yelling now.
• Use cd to get to other directories on your computer and then use ls to see what’s in
them.
• Update your notebook with new questions. I know you probably have some, because I’m
not covering everything about this command.
• Remember that if you get lost, then use ls and pwd to gure out where you are, then go
to where you need to be with cd.
Do This
Linux/OS X
Exercise 7 Session
$ cd temp
$ ls
stuff
$ cd stuff/things/frank/joe/alex/john/
$ cd ..
$ rmdir john
$ cd ..
$ rmdir alex
$ cd ..
$ ls
joe
$ rmdir joe
$ cd ..
$ ls
frank
$ rmdir frank
$ cd ..
$ ls
things
$ rmdir things
$ cd ..
$ ls
stuff
$ rmdir stuff
$ pwd
~/temp
$
WARNING! If you try to do rmdir on Mac OS X and it refuses to remove the directory
even though you are positive it’s empty, then there is actually a le in there called
.DS_Store. In that case, type rm -rf <dir> instead (replace <dir> with the direc-
tory name).
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 271 — #23
Windows
Exercise 7 Windows Session
> cd temp
> ls
Directory: C:\Users\zed\temp
> cd stuff/things/frank/joe/alex/john/
> cd ..
> rmdir john
> cd ..
> rmdir alex
> cd ..
> rmdir joe
> cd ..
> rmdir frank
> cd ..
> ls
Directory: C:\Users\zed\temp\stuff
Directory: C:\Users\zed\temp
Path
----
C:\Users\zed\temp
> cd ..
>
In this example you’ll learn how to remove a directory. It’s easy. You just go to the directory right
above it, then type rmdir <dir>, replacing <dir> with the name of the directory to remove.
Do More
• Make 20 more directories and remove them all.
• Make a single path of directories that is 10 deep and remove them one at a time just like
I did.
• If you try to remove a directory with content you will get an error. I’ll show you how to
remove these in later exercises.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 273 — #25
Do This
Linux/OS X
Exercise 8 Session
$ cd temp
$ mkdir -p i/like/icecream
$ pushd i/like/icecream
~/temp/i/like/icecream ~/temp
$ popd
~/temp
$ pwd
~/temp
$ pushd i/like
~/temp/i/like ~/temp
$ pwd
~/temp/i/like
$ pushd icecream
~/temp/i/like/icecream ~/temp/i/like ~/temp
$ pwd
~/temp/i/like/icecream
$ popd
~/temp/i/like ~/temp
$ pwd
~/temp/i/like
$ popd
~/temp
$ pushd i/like/icecream
~/temp/i/like/icecream ~/temp
$ pushd
~/temp ~/temp/i/like/icecream
$ pwd
~/temp
$ pushd
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 274 — #26
~/temp/i/like/icecream ~/temp
$ pwd
~/temp/i/like/icecream
$
Windows
Exercise 8 Windows Session
> cd temp
> mkdir -p i/like/icecream
Directory: C:\Users\zed\temp\i\like
Path
----
C:\Users\zed\temp
Path
----
C:\Users\zed\temp\i\like
Path
----
C:\Users\zed\temp\i\like\icecream
> popd
> pwd
Path
----
C:\Users\zed\temp\i\like
> popd
>
The pushd command takes your current directory and ”pushes” it into a list for later, then it
changes to another directory. It’s like saying, ”Save where I am, then go here.”
The popd command takes the last directory you pushed and ”pops” it off, taking you back there.
Finally, on UNIX, the command pushd, if you run it by itself with no arguments, will switch be-
tween your current directory and the last one you pushed. It’s an easy way to switch between two
directories. This does not work in PowerShell.
Do More
• Use these commands to move around directories all over your computer.
• Remove the i/like/icecream directories and make your own, then move around in
them.
• Explain to yourself the output that pushd and popd will print out for you. Notice how it
works like a stack?
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 276 — #28
• You already know this, but remember that mkdir -p will make an entire path even if all
the directories don’t exist. That’s what I did very rst for this exercise.
Do This
Linux/OS X
Exercise 9 Session
$ cd temp
$ touch iamcool.txt
$ ls
iamcool.txt
$
Windows
Exercise 9 Windows Session
> cd temp
> New-Item iamcool.txt -type file
> ls
Directory: C:\Users\zed\temp
>
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 277 — #29
Do More
• UNIX: Make a directory, change to it, and then make a le in it. Then move up one level
and run the rmdir command in this directory. You should get an error. Try to understand
why you got this error.
• Windows: Do the same thing, but you won’t get an error. You’ll get a prompt asking if
you really want to remove the directory.
Do This
Linux/OS X
Exercise 10 Session
$ cd temp
$ cp iamcool.txt neat.txt
$ ls
iamcool.txt neat.txt
$ cp neat.txt awesome.txt
$ ls
awesome.txt iamcool.txt neat.txt
$ cp awesome.txt thefourthfile.txt
$ ls
awesome.txt iamcool.txt neat.txt thefourthfile.txt
$ mkdir something
$ cp awesome.txt something/
$ ls
awesome.txt iamcool.txt neat.txt something thefourthfile.txt
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 278 — #30
$ ls something/
awesome.txt
$ cp -r something newplace
$ ls newplace/
awesome.txt
$
Windows
Exercise 10 Windows Session
> cd temp
> cp iamcool.txt neat.txt
> ls
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp
> ls something
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 280 — #32
Directory: C:\Users\zed\temp\something
Directory: C:\Users\zed\temp\newplace
>
I’m going to tell you a secret about programmers and system administrators now: they are lazy.
I’m lazy. My friends are lazy. That’s why we use computers. We like to make computers do boring
things for us. In the exercises so far you have been typing repetitive boring commands so that you
can learn them, but usually it’s not like this. Usually if you nd yourself doing something boring
and repetitive, there’s probably a programmer who has gured out how to make it easier. You just
don’t know about it.
The other thing about programmers is they aren’t nearly as clever as you think. If you overthink
what to type, then you’ll probably get it wrong. Instead, try to imagine what the name of a com-
mand is and try it. Chances are that it’s a name or some abbreviation similar to what you thought
it was. If you still can’t gure it out intuitively, then ask around and search online. Hopefully it’s
not something really stupid like ROBOCOPY.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 281 — #33
Do More
• Use the cp -r command to copy more directories with les in them.
• Find these les in your graphical user interface and open them in a text editor.
• Notice how sometimes I put a / (slash) at the end of a directory? That makes sure the le
is really a directory, so if the directory doesn’t exist I’ll get an error.
Do This
Linux/OS X
Exercise 11 Session
$ cd temp
$ mv awesome.txt uncool.txt
$ ls
newplace uncool.txt
$ mv newplace oldplace
$ ls
oldplace uncool.txt
$ mv oldplace newplace
$ ls
newplace uncool.txt
$
Windows
Exercise 11 Windows Session
> cd temp
> mv awesome.txt uncool.txt
> ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 282 — #34
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp
Directory: C:\Users\zed\temp\newplace
> ls
Directory: C:\Users\zed\temp
>
Do More
• Open your text editor and type some stuff into a new le. On OS X this could be
TextWrangler. On Windows this might be Notepad++. On Linux this could be gedit. Any
editor will work.
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 284 — #36
• In your shell use the commands you know to copy this le to your temp directory that
you’ve been working with.
Do This
Linux/OS X
Exercise 12 Session
$ less test.txt
[displays file here]
$
Windows
Exercise 12 Windows Session
WARNING! In the output I’m showing [displays file here] to ”abbreviate” what
that program shows. I’ll do this when I mean to say, ”Showing you the output of
this program is too complex, so just insert what you see on your computer here and
pretend I did show it to you.” Your screen will not actually show this.
Do More
• Open your text le again and repeatedly copy-paste the text so that it’s about 50–100
lines long.
• Now do the exercise again, but this time page through it. On UNIX you use the spacebar
and w (the letter w) to go down and up. Arrow keys also work. On Windows, just hit the
spacebar to page through.
• The cp command will overwrite les that already exist, so be careful when copying les
around.
Do This
Linux/OS X
Exercise 13 Session
$ less test2.txt
[displays file here]
$ cat test2.txt
I am a fun guy.
Don't you know why?
Because I make poems,
that make babies cry.
$ cat test.txt
Hi there this is cool.
$
Windows
Exercise 13 Windows Session
Remember that when I say [displays file here], I’m abbreviating the output of that command
so I don’t have to show you exactly everything.
Do More
Do This
Linux/OS X
Exercise 14 Session
$ cd temp
$ ls
uncool.txt iamcool.txt neat.txt something thefourthfile.txt
$ rm uncool.txt
$ ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 287 — #39
Windows
Exercise 14 Windows Session
> cd temp
> ls
Directory: C:\Users\zed\temp
> rm uncool.txt
> ls
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 288 — #40
Directory: C:\Users\zed\temp
> rm iamcool.txt
> rm neat.txt
> rm thefourthfile.txt
> ls
Directory: C:\Users\zed\temp
Do More
• Clean up everything in temp from all the exercises so far.
• Write in your notebook to be careful when running recursive remove commands on les.
Linux/OS X
Exercise 23 Session
$ exit
Windows
Exercise 23 Windows Session
> exit
Do More
For your last set of exercises, I want you to use the help system to look up a set of commands you
should research and learn how to use on your own.
• xargs
• sudo
• chmod
• chown
“Shaw_AppendixA” — 2014/11/7 — 18:37 — page 290 — #42
• forfiles
• runas
• attrib
• icacls
Find out what these are, play with them, and then add them to your index cards.
PowerShell References
On Windows, there’s really only PowerShell. Here’s a list of useful links related to PowerShell:
291
INDEX
Index
Symbols [ (left bracket), opening arrays with, 106–108
" (double quotes) ] (right bracket), closing arrays with, 106–108
escaping, 38 > (prompts), 50–51
strings and, 28, 33
variables and, 30 Numbers
' (single quotes) 2-dimensional (2D) arrays, 108
escaping, 38 8080 port, 219–223
strings and, 33
A
variables and, 30
Addresses, de ned, 225
" " " (triple quotes), 37–38
Advanced user input
/ (forward-slash) characters, 38–40
exceptions in, 206
\ (backslash) characters, 38–40
game lexicon and, 204–206
_ (underscore) characters, 24
introduction to, 204
|| (or) expressions, 91–96
lexicon types in, 205
+= (increment by) operators, 71–72, 99
numbers in, 206
= (equal) characters
questions about, 210
== vs., 25
sentence breaks in, 204–205
ARGV and, 46–51
Study Drills on, 209
in asking questions of users, 42
testing rst, 206–207
escaping quotes, 38
testing procedures, 207–209
format strings and, 34–37 writing scanners in, 205
naming variables with, 24–26 Advice for programmers, 246–247
printing variables with, 28–29 After inheritance, 180–182
returning values from functions with, 74–76 Algorithms, 140
setting variables to numbers, 44–45 Analysis
setting variables to strings, 30–33 of game engines. See Game engine analysis
== (double equal) characters, 25, 92–96 of games, 188–189, 191
! (not) expressions, 91–96 object-oriented. See Object-oriented
!= (not equal) characters, 91–96 analysis
# (pound) characters, 18–19 top down versus bottom up, 170–176
## ?? comments, 159–161 And (&&) expressions, 91–96
#{} (format activators), 28, 35 Argument variable (ARGV). See ARGV
% (modulus) operators, 22, 35 (argument variable)
%{} (format activators), 35 ArgumentError, 206
&& (and) expressions, 91–96 Arguments
*args (asterisk args), 63–65 *args, 63–65
@ (object scope), 125, 149–151 ARGV. See ARGV (argument variable)
“Shaw_Index” — 2014/11/8 — 17:18 — page 292 — #2
292 INDEX
INDEX 293
294 INDEX
INDEX 295
296 INDEX
INDEX 297
L M
Launchpad.net, 80 Mac OS X
Layout templates, 228–229 cat (stream le) in, 285
Learn C the Hard Way, 242 cd (change directory) in, 260–261
Learn Python the Hard Way, command line tools in, generally, 252–253
4, 242 cp (copy le) in, 277–278
Learn Ruby the Hard Way, 3–4 exit (exit terminal) in, 289
Learning programming languages, 243–244 rst programs on, 12, 14
Learning Ruby, overview. See Hard way less command in, 284
overview ls (list directory) in, 265
Left bracket ([), opening arrays with, mkdir (make directory) in, 257
106–108 mv (move le) in, 281
Lexicon. See Game lexicon popd (return to saved location) in, 273–274
“Shaw_Index” — 2014/11/8 — 17:18 — page 298 — #8
298 INDEX
INDEX 299
300 INDEX
Questions asked of users. See Asking questions learning, generally. See Hard way overview
of users setting up, 6–11
Ruby on Rails, 242
R RubyMotion, 242
rake test Ruby-Processing, 242
automated testing with, 199–202 Rules
setting up, 194 for if- statements, 120
syntax errors in, 202 for for-loop, 120
websites and, 230, 232 for while-loop, 120
Rakefile, 193–194, 199–202 Running les, 13, 15
.rb suf x, 12
Reading code S
for les. See Reading les Save location, go to new location (pushd),
in object-oriented programming, 153–156 273–276
resources for, 80–81 Scanners, 205
in Ruby, generally, 2 Searching Internet, 10
symbols in, 126 Sentences
Reading les breaks in, 204–205
backward, 24–26 creating, generally, 212
exercises in, 52–53, 56–57 exceptions in, 213
questions about, 54, 58 grammar in, 213
read command for, 56 match and peek in, 212–213
readline command for, 56 parsers in, 213–216
Study Drills on, 53, 57–58 questions about, 217
Refactoring game engines, 232–237 Study Drills on, 217
References, 242, 290 testing of, 217
Re ning code, 169–170 Servers, de ned, 226
Remove directory (rmdir), 269–272 Session-based game engines, 238–241
Remove le (rm), 286–289 Sessions, 237–238
Requests, de ned, 225–226 set, 141–142
require, 148–149 Setup
Researching game concepts, 166. See also for command line tools, 251
Game engine analysis generally, 6
Responses, de ned, 226 Internet searches for, 10
Return to saved location (popd), 273–276 on Linux, 8–10
Right bracket (]), closing arrays with, on Mac OS X, 6–7
106–108 warnings about, 10–11
rm (remove le), 286–289 on Windows, 7–8
rmdir (remove directory), 269–272 Shells, 249
Room class, 232–237 Sinatra
Ruby, introduction to browser interactions with, 220
rst programs in, 12–17 errors in, 221–222
idiomatic Ruby, 11 ”Hello World” project in, 219–220
“Shaw_Index” — 2014/11/8 — 17:18 — page 301 — #11
INDEX 301
302 INDEX
INDEX 303
The Addison-Wesley
Professional Ruby Series
informit.com/ruby
This tutorial will reward you for every minute you put into it. Soon,
you’ll know one of the world’s most powerful, popular programming
languages. You’ll be a Python programmer.
THIS PRODUCT
informit.com/register
informIT.com
THE TRUSTED TECHNOLOGY LEARNING SOURCE
Addison-Wesley | Cisco Press | Exam Cram
IBM Press | Que | Prentice Hall | Sams