5

Case statement:

case x
when 1
  "one"
when 2
  "two"
when 3
  "three"
else
  "many"
end

is evaluated using the === operator. This operator is invoked on the value of the when expression with the value of the case expression as the argument. The case statement above is equivalent to the following:

if 1 === x
  "one"
elsif 2 === x
  "two"
elsif 3 === x
  "three"
else
  "many"
end

In this case:

A = 1
B = [2, 3, 4]
case reason
when A
  puts "busy"
when *B
  puts "offline"
end

the when *B part cannot be rewritten to *B === 2.

Is this about the splat operator? The splat operator is about assignment, not comparison. How does case statement handle when *B?

sawa
  • 165,429
  • 45
  • 277
  • 381
X. Wang
  • 973
  • 1
  • 11
  • 21
  • 2
    A minor difference between your first and second example: if `x` is a method, it is only called once in the first example but up to three times in the second example. – Stefan Jun 15 '17 at 08:35

1 Answers1

6

But the splat operator is about assignment, not comparison.

In this case, * converts an array into an argument list:

when *[2, 3, 4]

is equivalent to:

when 2, 3, 4

Just like in a method call:

foo(*[2, 3, 4])

is equivalent to:

foo(2, 3, 4)
Stefan
  • 109,145
  • 14
  • 143
  • 218