理解范围和数组中的 ruby splat
我试图理解 *(1..9)
和 [*1..9]
之间的区别
如果我将它们分配给变量,它们的工作方式相同
splat1 = *(1..9) # splat1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
splat2 = [*1..9] # splat2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
但是当我尝试直接使用 *(1..9)
和 [*1..9]
时,事情变得很奇怪。
*(1..9).map{|a| a.to_s} # syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'
[*1..9].map{|a| a.to_s} # ["1", "2", "3"...]
我猜部分问题在于操作员的优先级?但我不太确定发生了什么事。为什么我无法使用 *(1..9)
,就像我可以使用 [*1..9]
一样?
I'm trying to understand the difference between *(1..9)
and [*1..9]
If I assign them to variables they work the same way
splat1 = *(1..9) # splat1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
splat2 = [*1..9] # splat2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
But things get weird when I try to use *(1..9)
and [*1..9]
directly.
*(1..9).map{|a| a.to_s} # syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'
[*1..9].map{|a| a.to_s} # ["1", "2", "3"...]
I'm guessing part of the problem is with operator precidence? But I'm not exactly sure what's going on. Why am I unable to use *(1..9)
the same I can use [*1..9]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题在于 splat 只能用作左值,也就是说它必须被某些东西接收。
因此,您的
*(1..9).map
示例失败,因为没有 splat 的接收者,但[*1..9].map
有效,因为您正在创建的数组是 splat 的接收者。更新:
有关此线程的更多信息(尤其是最后一条评论): 哪里使用 ruby splat 运算符合法吗?
I believe the problem is that splat can only be used as an lvalue, that is it has to be received by something.
So your example of
*(1..9).map
fails because there is no recipient to the splat, but the[*1..9].map
works because the array that you are creating is the recipient of the splat.UPDATE:
Some more information on this thread (especially the last comment): Where is it legal to use ruby splat operator?