Operators
Prerequisites: Booleans and nil
An operator is a symbol that performs an action on values, like +
for adding or > for comparing.
Arithmetic
+, -, *, /, % (remainder), ** (power) — covered in the
Numbers lesson.
Assignment shortcuts
score = 10
score += 5 # score = score + 5
score -= 2 # score = score - 2
score *= 2 # score = score * 2
p score
26
||= assigns only if the variable is currently nil or false — a
very common Ruby idiom for defaults:
nickname = nil
nickname ||= "Guest"
p nickname
"Guest"
Comparison
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
> < |
greater / less than |
>= <= |
greater / less or equal |
<=> |
"spaceship": -1, 0, or 1 |
The spaceship operator returns -1 if the left side is smaller, 0 if
they're equal, and 1 if it's bigger. Ruby uses it for sorting.
Logical
age = 20
has_ticket = true
p age >= 18 && has_ticket
p age < 13 || age > 65
p !has_ticket
true
false
false
&&(and) is true only if both sides are true.||(or) is true if either side is true.!(not) flips true and false.
Ruby also has the words and, or, and not, but they have lower
precedence than = and behave surprisingly in assignments. Stick to
&&, ||, and ! in conditions.
Common mistakes
- Writing
=(assignment) instead of==(comparison) in a condition.if x = 5assigns 5 and is always true; Ruby prints a warning.
Practice
A shop gives free delivery when an order is over 50, or when the
customer is a member. With total = 42 and member = true, print
whether delivery is free.
Show solution
total = 42
member = true
p total > 50 || member
true