谁能给我解释一下这个数组声明吗?

发布于 2024-08-12 06:25:32 字数 167 浏览 7 评论 0原文

只是想知道数组中最后一个逗号是否存在之间的区别(如果有的话)

>> [1,2,3]
=> [1, 2, 3]

>> [1,2,3,]
=> [1, 2, 3]

第二个数组仍然有效,没有引发异常

谢谢

just wondering the difference between the presence of the last comma in the array, if there is any at all

>> [1,2,3]
=> [1, 2, 3]

>> [1,2,3,]
=> [1, 2, 3]

The second array still works, no exception raised

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

似梦非梦 2024-08-19 06:25:32

没有什么区别。在 Ruby 中,您可以自由地向数组添加尾随逗号。它使语法如下:

a = [
  1,
  2,
  3,
]

在某些情况下更好一点(例如,如果您想添加一个元素,您只需添加一个 4, 行,而不必担心检查逗号在最后一行)。

There's no difference. In Ruby, you're free to add a trailing comma to an array. It makes syntax like this:

a = [
  1,
  2,
  3,
]

A bit nicer, in some cases (e.g., if you want to add an element, you simply add a 4, line and don't have to worry about checking for a comma on the last line).

青芜 2024-08-19 06:25:32

这不是一个错误,只是一个空值(被编译器忽略),但我建议您阅读 了解 Ruby 数组

It isn't a error, just a empty value(ignored by the compiler), but I suggest you to read Understanding Ruby Arrays

单调的奢华 2024-08-19 06:25:32

数组没有什么特别的。

[1,2,3]

相同,

Array.[](1,2,3)

所以值只是方法调用参数。这同样适用于

{a: 1, b: 2}

which 与 is 相同

Hash.[](:a, 1, :b, 2)

方法调用参数中允许使用尾随逗号的原因只是因为 Ruby 就是这样设计的,出于 @mipadi 提到的方便原因。

There is nothing special about arrays.

[1,2,3]

is the same as

Array.[](1,2,3)

so the values are just method call parameters. The same applies to

{a: 1, b: 2}

which is the same as

Hash.[](:a, 1, :b, 2)

And the reason trailing commas are allowed in method-call parameters is just because Ruby is designed like that, for the reasons of convenience that @mipadi mentioned.

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