How to Add Memory in Ruby by Storing Results in Variables

By Christopher Haupt

In Ruby, you typically name variables using lowercase letters, numbers, and underscores (_). Ruby expects a variable to start with a lowercase letter, and then you can use any combination of other lowercase letters, numbers, or the underscore. Ruby convention is to use “snakecase” when naming a variable. Snakecase splits up words with an underscore, kind of like using a blank space between words in an English sentence.

Computers give you not only the power to calculate, but also the ability to store information for later retrieval. You use variables to name a piece of memory, store information in that memory, and at some later time, retrieve the information again.

Here are some examples of variables:

hello_world_title
programmer1
blue_eyed_cat_name
b
a2

The last two examples, b and a2, are perfectly valid but what they’re used for is a little mysterious. Use variable names that are meaningful to you.

The basic naming used here works for local variables. You can use some additional symbols for other purposes.

To store data in a variable in Ruby, you “assign” the data to a variable using an equal sign (=):

2.2.2 :029 > age_of_my_dog = 4
=> 4

Unlike in math class, the equal sign here doesn’t mean that the left side is equivalent to the right side (there is another symbol used for that purpose). Instead, think of that equal sign as meaning “move the data on the right into the memory named with the variable on the left.”

To get the data back out of the variable, you just use the variable name as if you typed the data in directly:

2.2.2 :030 > age_of_my_dog * 7
=> 28

You can assign the results of the calculation into a new variable:

2.2.2 :031 > dogs_age_in_people_years = age_of_my_dog * 7
=> 28

Ruby is pretty generous with respect to what you can name your variables. Almost anything goes. One of the few rules is that the name must not conflict with any of Ruby’s built-in names for its commands. See the following for a list. If you do this accidentally, you get a syntax error,.

BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return while
def in self __FILE__
defined? module super __LINE__