TExcelTAD
Home › Ruby › Ruby Variables

Ruby Variables

A variable is a name that points to a value. In Ruby you create a variable simply by assigning to it — there is no var, let or type declaration.

Creating variables

ruby · try it yourself
planet = "Mars"
moons = 2
gravity = 3.72
habitable = false

puts planet
puts moons
puts gravity
puts habitable
Mars
2
3.72
false

The = sign means "make this name point to this value". You can reassign a variable at any time, even to a value of a different type, because Ruby is dynamically typed:

ruby · try it yourself
box = 10
puts box.class
box = "ten"
puts box.class
box = [1, 0]
puts box.class
Integer
String
Array

Naming rules

  • Local variable names start with a lowercase letter or _.
  • They may contain letters, digits and underscores.
  • Use snake_case for multi-word names: first_name, items_in_cart.
  • They cannot be reserved words such as end, class or def.
Valid Invalid Why invalid
total 2nd_place starts with a digit
user_name user-name - is the minus operator
_unused class reserved word
max_score2 Max capital letter makes it a constant

Multiple assignment

Ruby can assign several variables in one line, and swap values without a temporary variable:

ruby · try it yourself
x, y, z = 1, 2, 3
puts "#{x} #{y} #{z}"

x, y = y, x
puts "after swap: x=#{x}, y=#{y}"

first, *rest = [10, 20, 30, 40]
p first
p rest

a = b = 0
puts a + b
1 2 3
after swap: x=2, y=1
10
[20, 30, 40]
0

The * (splat) in *rest collects "everything else" into an array.

Shorthand assignment

Operator Same as
n += 2 n = n + 2
n -= 2 n = n - 2
n *= 2 n = n * 2
n /= 2 n = n / 2
name ||= "guest" assign only if name is nil or false
ruby · try it yourself
count = 5
count += 3
count *= 2
puts count

nickname = nil
nickname ||= "anonymous"
puts nickname

nickname ||= "never used"
puts nickname
16
anonymous
anonymous

Note: Ruby has no ++ or -- operators. Write i += 1 instead.

Variables are references

A variable does not contain an object; it refers to one. Two variables can refer to the same object, so a change made through one is visible through the other:

ruby · try it yourself
original = "tea"
alias_name = original
alias_name << " with milk"   # << changes the string in place

puts original
puts original.equal?(alias_name)

copy = original.dup
copy << " and sugar"
puts original
puts copy
tea with milk
true
tea with milk
tea with milk and sugar

Use dup when you want an independent copy. Reassignment (alias_name = "coffee") never affects the other variable — it just points the name somewhere else.

Kinds of variables

The first character of a name tells Ruby its scope:

Kind Example Visible in
Local price The current method, block or file
Instance @price One object (see the OOP lessons)
Class @@count A class and its subclasses
Global $debug Everywhere (avoid!)
Constant TAX_RATE Its class/module or the whole program

Constants

A name starting with a capital letter is a constant. Ruby lets you reassign it, but prints a warning — constants are meant to stay the same:

ruby · try it yourself
TAX_RATE = 0.21
price = 100
puts price * (1 + TAX_RATE)
puts TAX_RATE.frozen?
121.0
true

(Floats are always frozen, so frozen? is true here regardless.)

Local variable scope

A method has its own fresh set of local variables. It cannot see the locals defined outside it:

ruby · try it yourself
greeting = "hello"

def shout
  defined?(greeting) ? greeting.upcase : "no greeting here"
end

puts shout
no greeting here

Blocks (do ... end, { ... }) are different: they can see the surrounding local variables. You will see that in the Blocks & yield lesson.

Test yourself

Which line correctly swaps a and b?

  1. a = b; b = a
  2. a, b = b, a
  3. swap(a, b)
  4. a <=> b

What does name ||= "guest" do?

  1. Always sets name to "guest"
  2. Sets name to "guest" only if it is nil or false
  3. Compares name with "guest"
  4. Raises an error if name exists

How do you increase i by one in Ruby?

  1. i++
  2. ++i
  3. i += 1
  4. inc(i)