Understanding ruby splat in ranges and arrays
Asked Answered
N

1

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

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

Nostology answered 26/9, 2011 at 15:23 Comment(2)
p *(1..9).map{|a| a.to_s} works okTurpeth
Similarly, ([*1..9]).map should work fine; however, I think the explicit to_a method is more clear and essentially just as concise.Chronicle
T
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?

Tabethatabib answered 26/9, 2011 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.