Expand All

Variables

A variable is a way to name a piece of data so we can do things with it. It can hold all kinds of things - words, numbers, the result of a function, and even a function itself.

Goals

  • Understand what a variable is for

  • Store data in variables

  • Replace data in an existing variable

Step 1

Start up irb.

Type this in the terminal:
irb

Step 2

Type this in irb:
my_variable = 5

This creates a new variable called my_variable and stores the value 5 in it.

Let's confirm that. To see what value a variable holds, type its name.

Type this in irb:
my_variable
Expected result:
5
Type this in irb:
another_variable = "hi"

This creates another variable and stores the value "hi" in it.

Step 3

Type this in irb:
my_variable = 10

my_variable has a new value.

Type this in irb:
my_variable
Expected result:
10

Step 4

Type this in irb:
apples = 5
bananas = 10 + 5
fruits = 2 + apples + bananas
bananas = fruits - apples

Variables are assigned a value using a single equals sign (=).

The right side of the equals sign is evaluated, and the result is assigned to the variable named on the left side of the equals.

Step 5

You've created a lot of variables. Let's see the list.

Type this in irb:
local_variables
Expected result:
[:bananas, :fruits, :apples, :another_variable, :my_variable]

Here Ruby gives you a list of variables you've defined in irb so far. This might be useful for when you want to see what variable names are already in use.

Step 6

The opposite of a variable is constant - a value that doesn't change. Numbers, strings, nil, true, and false are constants.
Check out what happens if you assign a value to a constant."

Type this in irb:
  true = false
  1 = 1
  "a" = 1

(Notice in the last example we put the a in quotation marks to make it a string.)

Step 7

There are some rules about what you can name a variable.

Try making variables with the following kinds of names names in irb:

  • all letters (like 'folders')

  • all numbers (like '2000')

  • an underscore (like 'first_name')

  • a dash (like 'last-name')

  • a number anywhere (like 'y2k')

  • a number at the start (like '101dalmations')

  • a number at the end (like 'starwars2')

Which worked? Which didn't?

Step 8

Variables can hold the result of a function.

Type this in irb:
shouting = "hey, you!".upcase

Explicación

Variables allow you to store data so you can refer to it by name later. The data you store in variables will persist as long as your program keeps running and vanish when it stops.

Next Step: