9 views
What's the return value of the following Ruby 3 code?
x = nil y = "Ruby" x || y && "Rails" # => ???
The correct answer is
"Ruby"
"Rails"
nil
false
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
The code given might seem a bit confusing at first glance due to the combined use of logical operators ||
(OR) and &&
(AND).
Understanding how these operators work and their precedence in Ruby is key to determining the output.
In the provided code, we have:
x = nil y = "Ruby" p x || y && "Rails"
To evaluate the expression x || y && "Rails"
, we need to consider the order of precedence of the logical operators. In Ruby, the &&
operator has higher precedence than ||
.
This means that y && "Rails"
will be evaluated first, and then the result will be used in the x || ...
expression.
Let’s break it down step by step:
y && "Rails"
The &&
operator returns the second operand if both operands are truthy.
Here, y
is assigned the value "Ruby"
, which is a truthy value. The second operand is "Rails"
, which is also truthy. Therefore, y && "Rails"
evaluates to "Rails"
.
x || ...
Now that we know y && "Rails"
evaluates to "Rails"
, we can substitute it back into the original expression: x || "Rails"
.
The ||
operator returns the first truthy value it encounters. In this case, x
is nil
, which is not truthy. Therefore, the expression evaluates to the second operand, which is "Rails"
.
So, the correct answer is: "Rails"
The &&
operator binds more tightly than ||
, which is why y && "Rails"
is evaluated first.
If you had evaluated from left to right without considering precedence, you might have incorrectly concluded that "Ruby"
was the result.
Understanding precedence rules is crucial for correctly interpreting and predicting the behavior of Ruby code.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©