604 views
What's the return value of the following Ruby code?
y = false y ||= 42 y # => ???
The correct answer is
nil
false
42
true
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
Let’s analyze this simple snippet:
y = false y ||= 42 # => 42
||=
is shorthand for:
y = y || 42
So Ruby evaluates y || 42
. In Ruby, only two values are falsy: false
and nil
.
Everything else (0
, ""
, []
, {}
, etc.) is truthy.
On the first line, y
is assigned false.
Then y ||= 42
is the same as y = (false || 42)
.
false || 42
evaluates to 42
.
So y
now holds 42
.
Here is quick note on Logical OR algebra
The logical OR operator
||
follows this algebra:
true
|| anything →true
false
||x
→x
This is why false || 42
gives 42
.
Many expect false
to “stick,” but with ||=
Ruby treats false
just like nil
: it triggers assignment of the fallback value.
x = nil x ||= 100 x # => 100 a = "hello" a ||= "world" a # => "hello"
If the variable is nil
or false
, the fallback is assigned.
If the variable is any truthy value, it stays as it is.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©