Variables

Goals

  • Store data in variables
  • Replace data in an existing variable

Step 1

Start irb again

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.

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

This reassigns my_variable, which already exists, to 10.

Step 4

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

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

The right side of the equals sign is evaluated first, then the value is assigned to the variable named on the left side of the equals.

Step 5

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?

Explanation

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.

Next Step:

Back to irb