Variables and Strings
Store information and combine it with interpolation
So far your programs have only printed fixed text. Real programs need to remember information and reuse it, and that is exactly what variables are for. A variable is simply a name you choose to store a piece of information so you can use it later.
Creating a variable
In Ruby, you create a variable by picking a name and using a single equals sign to store a value inside it.
name = "Ava"
puts nameHere, name is the variable, and it now holds the string "Ava". Notice that when you print a variable, you do not put quotes around its name.
Variables can change
Variables are called variables because their value can vary, or change, over time.
name = "Ava"
puts name
name = "Sam"
puts nameThis program first prints "Ava" and then prints "Sam", because the variable name was updated in between.
Combining text with interpolation
Often you will want to mix a variable into a longer sentence. Ruby makes this easy with a feature called string interpolation. Inside a double-quoted string, you can place #{} around any variable, and Ruby will replace it with its value.
name = "Ava"
puts "Hello, #{name}! Welcome to Ruby."This prints "Hello, Ava! Welcome to Ruby." Ruby quietly swaps #{name} for whatever is stored in the variable before printing the line.
An important detail about quotes
Interpolation with #{} only works inside double-quoted strings, not single-quoted strings. That is one of the main reasons Ruby programmers reach for double quotes so often.
Good variable names describe what they hold, like name or favorite_color. Clear names make your code much easier to read later, even for you.
Quick check
Q1 What symbol is used to store a value in a Ruby variable?
Q2 Which of these correctly uses string interpolation?
Want to save your progress? It's free.
Create a free account