开发者

Understanding ruby splat in ranges and arrays

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', exp开发者_运维问答ecting 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]?


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜