Using splat operator with when
Asked Answered
A

1

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?

Allurement answered 15/6, 2017 at 8:5 Comment(1)
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.Fertilize
F
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)
Fertilize answered 15/6, 2017 at 8:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.