Chapter 3 Variables and Assignment

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Progress Checkpoint | TOC | Variables Point to Values 👉

So far, we’ve been writing some fairly simple programs with numbers and strings. As our programs get more and more complex, it’s going to be a lot easier if we can assign names to those numbers and strings. We call these names variables. In this chapter, we’ll learn how to use variables to make our programs easier to write and read.

Let’s say you wanted to print a string twice. With what you’ve learned so far, the only way to do it would be like this:

​1: puts ​"...you can say that again..."​ 
​2: puts ​"...you can say that again..."​
​<= ...you can say that again...
​ ...you can say that again...

That works, but I don’t want to type that string twice. I’m lazy. Plus, I might type it wrong the second time. Sure, we could copy and paste the string, but that’s not maximally lazy. What if we want to change the string later? We’d have to change it twice. Copy and paste is the opposite of the Don’t Repeat Yourself rule.

To store the string in your computer’s memory for use later in your program, you need to give the string a name. Programmers often refer to this process as assignment, and we call the names variables. A variable name can usually be almost any sequence of letters and numbers, but in Ruby, the first character of this name needs to be a…

--

--

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.