这在 Ruby 语言中意味着什么?
运行下面的代码,
a = [1, 2, 3, 4, 5]
head, *tail = a
p head
p tail
你会得到结果
1
[2, 3, 4, 5]
谁能帮我解释一下head,*tail = a
这个语句,谢谢!
Run the following code,
a = [1, 2, 3, 4, 5]
head, *tail = a
p head
p tail
You will get the result
1
[2, 3, 4, 5]
Who can help me to explain the statement head,*tail = a
, Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我根本不了解 Ruby,但我的猜测是该语句将列表
a
分成头(第一个元素)和其余部分(另一个列表),并将新值分配给变量头
和尾
。这种机制通常被称为(至少在 Erlang 中)模式匹配。
I don't know Ruby at all, but my guess is that the statement is splitting the list
a
into a head (first element) and the rest (another list), assigning the new values to the variableshead
andtail
.This mechanism is usually referred (at least in Erlang) as pattern matching.
首先,这是一个并行任务。在 ruby 中,您可以编写
a 为 1,b 为 2。您还可以使用它
来交换值(无需其他语言中所需的典型临时变量)。
星号 * 是打包/解包运算符。写入时
会将 1 分配给 a,将 2 分配给 b。通过使用星号,值 2,3 被打包到一个数组中并分配给 b:
First, it is a parallel assignment. In ruby you can write
and a will be 1 and b will be 2. You can also use
to swap values (without the typical temp-variable needed in other languages).
The star * is the pack/unpack operator. Writing
would assign 1 to a and 2 to b. By using the star, the values 2,3 are packed into an array and assigned to b:
head, *tail = a
表示将数组a
的第一个元素赋值给head
,其余元素赋值给>尾部。
*
,有时称为“splat 运算符”,可以对数组执行许多操作。当它位于赋值运算符 (=
) 的左侧时(如您的示例中所示),它仅表示“获取剩余的所有内容”。如果您在该代码中省略了 splat,它会这样做:
但是当您将 splat 添加到
tail
时,它意味着“未分配给先前变量的所有内容 (head< /code>),分配给
tail
。”head, *tail = a
means to assign the first element of the arraya
tohead
, and assign the rest of the elements totail
.*
, 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."If you omitted the splat in that code, it would do this instead:
But when you add the splat to
tail
it means "Everything that didn't get assigned to the previous variables (head
), assign totail
."