问题描述
运行以下代码,
a = [1, 2, 3, 4, 5]
head, *tail = a
p head
p tail
你会得到结果
1
[2, 3, 4, 5]
谁能帮我解释下语句head,*tail = a
,谢谢!
Who can help me to explain the statement head,*tail = a
, Thanks!
推荐答案
head, *tail = a
表示将数组的第一个元素 a
赋值给 head
,并将其余元素分配给 tail
.
head, *tail = a
means to assign the first element of the array a
to head
, and assign the rest of the elements to tail
.
*
,有时被称为splat 操作符",对数组做了很多事情.当它位于赋值运算符 (=
) 的左侧时,如您的示例所示,它仅表示保留所有剩余内容."
*
, sometimes called the "splat operator," does a number of things with arrays. When it's on the left side of an assignment operator (=
), as in your example, it just means "take everything left over."
如果您在该代码中省略了 splat,它将改为这样做:
If you omitted the splat in that code, it would do this instead:
head, tail = [1, 2, 3, 4, 5]
p head # => 1
p tail # => 2
但是当您将 splat 添加到 tail
时,它意味着所有没有分配给前面的变量 (head
),分配给 tail
."
But when you add the splat to tail
it means "Everything that didn't get assigned to the previous variables (head
), assign to tail
."
这篇关于这在 Ruby 语言中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!