The name of the legal variable _
. And something like *_
like *x
. The term "final underscore variable" actually refers to the last variable name in a comma-separated sequence of variables on the left side of the assignment operator, for example:
a, b, _ = [1, 2, 3, 4]
The splat operator has two uses:
- Enter an array into individual elements.
- Collect the elements into an array.
Which of these events depends on the context in which the splat operator is used.
Here are the examples that are said in the Ruby style guide:
a, b, _ = *foo
The final underscore variable is not needed in this example, because you can assign the first two elements foo
to variables a
and b
by writing:
a, b = *foo
, , , , , , a
b
.
, *
(: Cary Swoveland):
a, b = [1, 2, 3]
p a, b
--output:--
1
2
*
:
x, y, z = 10, [20, 30]
p x, y, z
--output:--
10
[20, 30]
nil
x, y, z = 10, *[20, 30]
p x, y, z
--output:--
10
20
30
, , *
.
:
a, _, _ = *foo
:
a, _, _ = *[1, 2, 3, 4]
p a, _
puts "-" * 10
a, _ = *[1, 2, 3, 4]
p a, _
--output:--
1
3
----------
1
2
, :
a, _, _
^ ^ ^
| | |
[1, 2, 3, 4]
, , a
. ?
a = *[1, 2, 3, 4]
p a
--output:--
[1, 2, 3, 4]
. . , , :
a, = *[1, 2, 3, 4]
p a
--output:--
1
:
a, *_ = *foo
:
a, = *foo
.
, :
, , , .
, - :
*a = *[1, 2, 3, 4]
p a
--output:--
[1, 2, 3, 4]
, a
, :
*a, _ = *[1, 2, 3, 4]
p a
--output:--
[1, 2, 3]
- :
*a, = *[1, 2, 3, 4]
--output:--
*a, = *[1, 2, 3, 4]
^
1.rb:6: syntax error, unexpected '\n', expecting :: or '[' or '.'
:
*a, b, _ = *foo
, foo b
.
:
a, _b = *[1, 2, 3, 4]
a, _b, = *[1, 2, 3, 4]
:
a, _b = *[1, 2, 3, 4]
p a, _b
puts "-" * 10
a, _b, = *[1, 2, 3, 4]
p a, _b
--output:--
1
2
----------
1
2
, _b
, _
b
. , Erlang, _
_b
b
, Ruby.
, - .