Ruby Operators
Operators are symbols that combine or compare values: +, ==, && and so on. A surprising fact about Ruby is that most operators are methods. 3 + 4 is really 3.+(4). That is why your own classes can define what + or == means for them.
p 3 + 4
p 3.+(4)
p "ab".*(3)7
7
"ababab"
Arithmetic operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
addition | 5 + 2 |
7 |
- |
subtraction | 5 - 2 |
3 |
* |
multiplication | 5 * 2 |
10 |
/ |
division | 5 / 2 |
2 |
% |
modulo | 5 % 2 |
1 |
** |
exponent | 5 ** 2 |
25 |
They also work on other types: "a" + "b", [1] + [2], "-" * 5, [1, 2, 3] - [2].
Assignment operators
=, plus the combined forms +=, -=, *=, /=, %=, **=, ||= and &&=:
total = 100
total -= 15
total *= 2
total %= 60
p total
cache = nil
cache ||= "computed"
p cache
name = "zoe"
name &&= name.capitalize # only runs if name is truthy
p name50
"computed"
"Zoe"
Comparison operators
| Operator | Meaning |
|---|---|
== |
equal value |
!= |
not equal |
> < >= <= |
greater / less |
<=> |
"spaceship": -1, 0 or 1 (or nil if not comparable) |
=== |
case equality (used by case/when) |
eql? |
equal value and same type |
equal? |
same object |
p 5 == 5.0
p 5.eql?(5.0)
p 3 <=> 7
p "b" <=> "a"
p 4 <=> "x"
p (1..10) === 5
p Integer === 5
p /ab/ === "cab"true
false
-1
1
nil
true
true
true
=== reads as "does the left side describe the right side?": a range contains the number, a class matches its instances, a regex matches the string. case/when uses exactly this operator.
Logical operators
| Operator | Meaning | Example |
|---|---|---|
&& |
and | age >= 18 && member |
|| |
or | admin || owner |
! |
not | !done |
Both && and || short-circuit and return one of their operands, not just true/false:
p true && "yes"
p nil && "never evaluated"
p nil || "fallback"
p false || nil
p "first" || "second"
p !nil"yes"
nil
"fallback"
nil
"first"
true
Note: Ruby also has the words
and,orandnot, but with very low precedence.x = true and falseassignstruetox! Use&&,||and!in expressions; reserveand/orfor control flow likesave or raise "failed".
Safe navigation &.
&. calls a method only if the receiver is not nil; otherwise it returns nil instead of raising an error:
user = {profile: nil}
p user[:profile]&.fetch(:city)
p "text"&.upcase
city = user[:profile]&.fetch(:city) || "unknown"
p citynil
"TEXT"
"unknown"
Other useful operators
| Operator | Example | Meaning |
|---|---|---|
? : |
n > 0 ? "pos" : "neg" |
ternary (inline if/else) |
.. / ... |
1..5, 1...5 |
inclusive / exclusive range |
<< |
arr << 4, str << "x" |
append (or bit shift for integers) |
defined? |
defined?(foo) |
is this name defined? |
& | ^ ~ |
6 & 3 |
bitwise operators on integers |
=~ |
"cat" =~ /a/ |
regex match position |
Precedence
From high to low, the most common ones are: ! → ** → unary - → * / % → + - → << >> → & → | ^ → > >= < <= → <=> == === != =~ → && → || → .. ... → ? : → assignment → not → and or.
p 2 + 3 * 4
p (2 + 3) * 4
p -2 ** 2
p 10 - 2 - 314
20
-4
5
-2 ** 2 is -(2 ** 2) because ** binds tighter than unary minus. When in doubt, add parentheses.
Test yourself
What does nil || "default" return?
- nil
- true
- "default"
- false
What does 5 <=> 9 return?
- true
- -1
- 1
- 4
What does user&.name do when user is nil?
- Raises NoMethodError
- Returns nil
- Returns an empty string
- Creates a user