这在 Ruby 语言中意味着什么?

发布于 2024-09-17 05:19:36 字数 199 浏览 4 评论 0原文

运行下面的代码,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

木落 2024-09-24 05:19:50

我根本不了解 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 variables head and tail.

This mechanism is usually referred (at least in Erlang) as pattern matching.

墨离汐 2024-09-24 05:19:48

首先,这是一个并行任务。在 ruby​​ 中,您可以编写

a,b = 1,2

a 为 1,b 为 2。您还可以使用它

a,b = b,a

来交换值(无需其他语言中所需的典型临时变量)。

星号 * 是打包/解包运算符。写入时

a,b = [1,2,3]

会将 1 分配给 a,将 2 分配给 b。通过使用星号,值 2,3 被打包到一个数组中并分配给 b:

a,*b = [1,2,3]

First, it is a parallel assignment. In ruby you can write

a,b = 1,2

and a will be 1 and b will be 2. You can also use

a,b = b,a

to swap values (without the typical temp-variable needed in other languages).

The star * is the pack/unpack operator. Writing

a,b = [1,2,3]

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:

a,*b = [1,2,3]
软的没边 2024-09-24 05:19:44

head, *tail = a 表示将数组a的第一个元素赋值给head,其余元素赋值给>尾部。

*,有时称为“splat 运算符”,可以对数组执行许多操作。当它位于赋值运算符 (=) 的左侧时(如您的示例中所示),它仅表示“获取剩余的所有内容”。

如果您在该代码中省略了 splat,它会这样做:

head, tail = [1, 2, 3, 4, 5]
p head # => 1
p tail # => 2

但是当您将 splat 添加到 tail 时,它意味着“未分配给先前变量的所有内容 (head< /code>),分配给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.

*, 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:

head, tail = [1, 2, 3, 4, 5]
p head # => 1
p tail # => 2

But when you add the splat to tail it means "Everything that didn't get assigned to the previous variables (head), assign to tail."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文