Chapter
4
Variables and Assignment
So far, whenever we have putsed a string
or a number, the thing we putsed is gone.
What I mean is, if we wanted to print something out twice, we
would have to type it in twice:
puts '...you can say that again...' |
puts '...you can say that again...' |
...you can say that again... |
...you can say that again... |
It would be nice if we could just type it in once and then hang on
to it…store it somewhere. Well, we can, of
course. It would have been insensitive to bring it up otherwise.
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 they call the names variables. A
variable name can usually be just about any sequence of letters
and numbers, but in Ruby the first character of this name needs to
be a lowercase letter. Let’s try that last program again, but
this time I will give the string the
name my_string (though I could just
as well have named it str
or myOwnLittleString
or henry_the_8th):
my_string = '...you can say that again...' |
puts my_string |
puts my_string |
...you can say that again... |
...you can say that again... |
Whenever you tried to do something to
my_string, the
program did it to
'...you can say that again...'
instead. You can think of the variable
my_string as
“pointing to” the string
'...you can say that again...'.
Here’s a slightly more motivated example:
name = 'Anya Christina Emmanuella Jenkins Harris' |
puts 'My name is ' + name + '.' |
puts 'Wow! ' + name |
puts 'is a really long name!' |
My name is Anya Christina Emmanuella Jenkins Harris. |
Wow! Anya Christina Emmanuella Jenkins Harris |
is a really long name! |
Also, just as we can assign an object to a variable,
we can reassign a different object to that variable.
(This is why we call them variables—what they point
to can vary.)
composer = 'Mozart' |
puts composer + ' was "da bomb" in his day.' |
|
composer = 'Beethoven' |
puts 'But I prefer ' + composer + ', personally.' |
Mozart was "da bomb" in his day. |
But I prefer Beethoven, personally. |
Of course, variables can point
to any kind of object, not just strings:
my_own_var = 'just another ' + 'string' |
puts my_own_var |
|
my_own_var = 5 * (1+2) |
puts my_own_var |
In fact, variables can point to just about anything…except
other variables. So, what happens if we try the following?
var1 = 8 |
var2 = var1 |
puts var1 |
puts var2 |
|
puts '' |
|
var1 = 'eight' |
puts var1 |
puts var2 |
On the second line, when we tried to
point var2
to var1, it really pointed
to 8 instead (just
like var1 was pointing to). Then on
the eighth line, we had var1 point to
the string 'eight', but
since var2 was never really pointing
at var1, it stays pointing at
the number 8. If you like to
think about these things visually, it might help to look at the figure Figure 1, Variables point to values.
Copyright © 2014, The Pragmatic Bookshelf.