Ruby Variables
A variable is a name that holds a value. A program can use the value by writing the name.
Store a value and print it
The = sign stores the text Ana in the variable name. The puts line prints the stored value.
name = "Ana"
puts nameA number in a variable
A variable can hold a number too. The puts line prints the number stored in score.
score = 42
puts scoreChange the value
The name stays the same here. A new value replaces the old value, and the second print shows it.
name = "Ana"
puts name
name = "Mina"
puts nameTwo variables in one program
Each variable holds its own value. The two puts lines print the values in order.
city = "Oslo"
age = 30
puts city
puts ageExample
name = "Ana"
city = "Oslo"
puts name
puts city
name = "Mina"
puts nameKey points
- A variable holds a value under a name.
- Use = to store a value in a variable.
- Variable names use snake_case in this course.
- snake_case joins words with underscores and uses small letters.
- A variable can hold a new value in place of the old one.
- Writing the name where a value is needed uses the stored value.
In this example, name holds Ana and city holds Oslo. The first two puts lines print those values. name then stores Mina, and the last puts line prints Mina.
Note
A variable needs no type word before its name.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
Which line stores the number 5 in a variable named score?