Using splat operator with
A business:
case x
when 1
"one"
when 2
"two"
when 3
"three"
else
"many"
end
evaluated using the operator ===
. This operator is called on the value of an expression when
with the value of the expression case
as an argument. The above example 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
part when *B
cannot be rewritten to *B === 2
.
What is this splat operator? The splat operator is an assignment, not a comparison. How does the case handle handle when *B
?
source to share
But the splat operator is an assignment, not a comparison.
In this case, *
converts the array to an argument list :
when *[2, 3, 4]
equivalent to:
when 2, 3, 4
As in the method call:
foo(*[2, 3, 4])
equivalent to:
foo(2, 3, 4)
source to share