开发者

Understanding ruby splat in ranges and arrays

开发者 https://www.devze.com 2023-04-07 10:11 出处:网络
I\'m trying to understand the difference between *(1..9) and [*1..9] If I assign them to variables they work the same way

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

精彩评论

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

关注公众号