the short answer
A Ruby variable is a name that points to a value. You make one by assigning to it, like name = "Sam", with no keyword and no type. The same variable can later point to a value of any type. Names are written in snake_case, like player_name. A name that starts with a capital letter is a constant, meant to stay the same.
A Ruby variable is a name for a value. You make one just by assigning to it, with no keyword and no type:
name = "Sam"
age = 9
height = 1.32
likes_cats = true
puts name
puts age
puts height
puts likes_catsSam
9
1.32
trueputs shows a value and moves to a new line. That is the whole idea: write a name, an equals sign and a value, then use the name wherever you need the value.
This guide shows how to check what kind of value a variable holds, put variables inside text, change them, mix text and numbers safely, and use nil and constants. It also covers the naming rules and the errors you will meet. Every example runs right here in your browser.
Making a variable
age = 9 has three parts:
ageis the name.=means point this name at this value. Read it as “becomes”, not “equals”.9is the value.
There is no semicolon at the end and no word like var in front. The variable exists from the moment you assign it, and not before.
What kind of value is it?
Ruby variables do not have types, but every value does. Ask a value with .class, and use p to see a value exactly as it would be written in code:
name = "Sam"
age = 9
p name
p age
puts name.class
puts age.class
puts 1.32.class
puts nil.class"Sam"
9
String
Integer
Float
NilClassp keeps the quotes around text, so you can tell the string "9" from the number 9 at a glance. That makes it the best tool when a variable is not doing what you expect.
Putting variables inside text
Inside double quotes, #{} swaps in the value of whatever is between the curly brackets. Inside single quotes, nothing is swapped:
name = "Sam"
age = 9
puts "#{name} is #{age}"
puts '#{name} is #{age}'Sam is 9
#{name} is #{age}This is called string interpolation. It works with numbers too, because Ruby turns the value into text for you.
Changing a variable
Assign again and the name points at the new value. It does not have to be the same type:
score = 10
score = score + 5
score += 1
puts score
score = "sixteen"
puts score
puts score.class16
sixteen
Stringscore += 1 is short for score = score + 1. Switching a variable from a number to text is allowed, but it makes code harder to follow, so most Ruby code keeps each variable to one kind of value.
Text and numbers do not mix by accident
Ruby will not quietly turn a number into text when you join them with +:
age = 9
puts "Age: " + ageTypeError: no implicit conversion of Integer into String (line 2)Convert on purpose instead. to_s turns a value into a string, and to_i turns text into a whole number:
age = 9
puts "Age: " + age.to_s
puts "5".to_i + 3
puts "5" + "3"Age: 9
8
53With two strings, + joins them, which is why the last line shows 53. Interpolation, "Age: #{age}", is usually the neatest choice of all.
Numbers and maths
Dividing one whole number by another keeps only the whole part. Make either number a float for the full answer:
puts 7 / 2
puts 7 / 2.0
puts 7 % 23
3.5
1% gives the remainder. Floats also store most decimals as a close approximation, so 0.1 + 0.2 shows as 0.30000000000000004. That is normal in most languages, not a Ruby bug.
nil: a variable with nothing in it
nil means no value at all. nil? asks whether a value is nil:
nickname = nil
p nickname
puts nickname.nil?nil
trueYou will see nil when something was not found, or when a variable was set up before its real value was known.
Two variables at once
Ruby can assign several variables in one line, and swap two values without a spare variable:
a, b = 1, 2
puts a
puts b
a, b = b, a
puts "#{a} #{b}"1
2
2 1Constants
A name that starts with a capital letter is a constant: a value that is meant to stay the same. Constants are usually written all in capitals, like MAX_LIVES = 3.
Ruby does let you change a constant, but it prints a warning that the constant was already initialised. The run boxes here do not show warnings, so changing a constant in one of them just prints the new value. On your own computer, treat that warning as a bug to fix.
Naming variables
The rules Ruby enforces:
- A variable name starts with a small letter or an underscore.
- The rest can be letters, digits and underscores, with no spaces.
- A capital first letter makes a constant, not a variable.
The habit Ruby code follows is snake_case: all small letters, with underscores between words, like likes_cats and player_name. You may also meet names that start with @, which belong to an object, and with $, which are global. Those come later, once local variables feel natural.
Where a variable can be seen
A variable made outside a method cannot be seen inside it. Each method has its own set of names:
greeting = "Hello"
def say_hi
puts greeting
end
say_hiNameError: undefined local variable or method 'greeting' for main (line 3)Pass the value in as an argument instead, as in def say_hi(greeting). Gwecode’s Ruby Level 1 has a lesson on giving a method information.
Common mistakes
A typo in the name
player_name = "Sam"
puts player_nmeNameError: undefined local variable or method 'player_nme' for main (line 2)Ruby checks for a method with that name too, which is why the message mentions both. Compare the spelling with the line where you made the variable.
Single quotes around #{}
puts 'Hello, #{name}' prints the curly brackets as they are. Interpolation only works in double quotes.
Joining a number to text with +
As shown above, "Age: " + 9 stops with a TypeError. Use "Age: #{age}" or age.to_s.
A capital letter by accident
Name = "Sam" makes a constant, not a variable. It works at first, but Ruby warns you as soon as you try to change it. Start variable names with a small letter.
Reading a variable before it exists
A variable only exists after the line that assigns it. Use it on an earlier line and you get the same NameError as a typo.
A short exercise
Sam saves £3 of pocket money every week. Make variables for the name, the weekly amount and the number of weeks, then print this line:
Sam will have £24 after 8 weeksTo try it out, open the playground from the button at the bottom of the page and choose Ruby.
One possible answer
name = "Sam"
weekly = 3
weeks = 8
total = weekly * weeks
puts "#{name} will have £#{total} after #{weeks} weeks"Sam will have £24 after 8 weeksInterpolation turns total and weeks into text for you, so there is no need for to_s.
Related reading
- PHP variables explained, another language where any variable can hold any type.
- C# variables explained, for the opposite approach, where every variable has a fixed type.
Your next step
Ruby’s creator set out to make programming enjoyable, and its variables show it: no keywords, no types, just names and values. Gwecode’s Ruby Level 1 starts with a variable as a labelled box, then moves on to text, maths, decisions, loops, arrays and methods of your own, one short lesson at a time. Its level check is a quiz game you build yourself and answer with gets. Every lesson is free and runs in your browser. Create a free account to keep your progress, and start with the lesson below.
practise this · ruby · lessonA variable is a labelled boxstart the lessonquestions
Do Ruby variables have types?
The values do, but the variables do not. A variable is just a name, and it can point to text now and a number later. Ask any value what it is with .class.
What is the difference between puts and p?
puts shows a value in a friendly way, for people. p shows it the way you would write it in code, so text keeps its quotes and nil shows as nil. p is handy for checking what a variable really holds.
Why does Ruby say undefined local variable or method?
Ruby met a name it does not know. Usually it is a typo, or a variable made outside a method being used inside one. Check the spelling against the line where you made it.
Can I change a Ruby constant?
Ruby lets you, but it prints a warning that the constant was already initialised. Constants are a promise to readers that a value stays the same, so treat that warning as a bug.
Why does "Age: " + 9 cause an error?
Ruby will not quietly turn a number into text. Convert it first with to_s, or put it inside the text with #{}, which converts it for you.
