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
planet = "Mars"
moons = 2
gravity = 3.72
habitable = false
puts planet
puts moons
puts gravity
puts habitableMars
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:
box = 10
puts box.class
box = "ten"
puts box.class
box = [1, 0]
puts box.classInteger
String
Array
Naming rules
- Local variable names start with a lowercase letter or
_. - They may contain letters, digits and underscores.
- Use
snake_casefor multi-word names:first_name,items_in_cart. - They cannot be reserved words such as
end,classordef.
| 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:
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 + b1 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 |
count = 5
count += 3
count *= 2
puts count
nickname = nil
nickname ||= "anonymous"
puts nickname
nickname ||= "never used"
puts nickname16
anonymous
anonymous
Note: Ruby has no
++or--operators. Writei += 1instead.
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:
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 copytea 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:
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:
greeting = "hello"
def shout
defined?(greeting) ? greeting.upcase : "no greeting here"
end
puts shoutno 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?
a = b; b = aa, b = b, aswap(a, b)a <=> b
What does name ||= "guest" do?
- Always sets name to "guest"
- Sets name to "guest" only if it is nil or false
- Compares name with "guest"
- Raises an error if name exists
How do you increase i by one in Ruby?
i++++ii += 1inc(i)