了解范围和数组中的 ruby​​ splat [英] Understanding ruby splat in ranges and arrays

查看:43
本文介绍了了解范围和数组中的 ruby​​ splat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 *(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]

但是当我尝试直接使用 *(1..9)[*1..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"...]

我猜部分问题出在运算符优先级上?但我不确定发生了什么.为什么我不能像使用 [*1..9] 一样使用 *(1..9)?

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]?

推荐答案

我认为问题是 splat 只能用作左值,也就是说它必须被某些东西接收.

I believe the problem is that splat can only be used as an lvalue, that is it has to be received by something.

所以您的 *(1..9).map 示例失败了,因为 splat 没有收件人,但是 [*1..9].map 有效,因为您正在创建的数组是 splat 的接收者.

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.

更新:关于此线程的更多信息(尤其是最后一条评论):哪里使用 ruby​​ splat 运算符是否合法?

UPDATE: Some more information on this thread (especially the last comment): Where is it legal to use ruby splat operator?

这篇关于了解范围和数组中的 ruby​​ splat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆