757 views
What's the return value of the following Ruby code?
a = [1, 2] res = [] case a.size when 2 then res << 1 when 2 then res << 2 end res # => ???
The correct answer is
[2]
[1]
[2, 1]
[1, 2]
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
The case
statement is used to evaluate the size of array a
. In this case, a.size
equals 2
.
The first when
clause checks if a.size
is 2
. Since it is, 1
is appended to the res
array.
The second when
clause also checks if a.size
is 2
.
However, in Ruby, case
statements execute only the first matching when
clause and then exit the case
block. Therefore, this second clause is never executed.
So the res
array ends up with just [1]
, because the first when
clause matched, and the second one was ignored.
Single Execution of when
Clauses
In a case
statement, only the first matching when
clause is executed.
Subsequent matching when
clauses are not evaluated, which is why res
contains only [1]
and not [2]
.
Order Matters
The order of when
clauses is crucial. If the order were reversed, res
would contain [2]
instead.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©