0

Why does

 a = *(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

but

*(1..10)
SyntaxError: unexpected '\n', expecting '.' or &. or :: or '['

(I'd have thought it would return the same as in the first case, but that it simply wouldn't do any assignment). Curious to know if the reason for this is ruby related, or more specifically related to splat (*)

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

2

I don't think of splat as a unary operator to be used on its own /w an expression like that.

It's syntax for assigning values to arguments in a method call:

def foo(a, b)
  puts a
  puts b
end

foo(*[:a, :b])

For setters, this means:

obj.my_attribute = *(1..10)

is sugar for the method:

obj.my_attribute=(*1..10)

It's also used inside Array literal expressions: [*1..10]

I was a little surprised to find that a = *(1..10) works because it's local variable assignment, but perhaps Ruby treats that the same way.

*(1..10) by itself, however, definitely isn't a method call. You should use (1..10).to_a.

Kache
  • 15,647
  • 12
  • 51
  • 79
  • Interesting. I got that approach from [here](https://stackoverflow.com/a/6587096/5783745) - assumed it was okay due to massive upvotes – stevec Sep 13 '20 at 13:58
  • 1
    Haha, you'll notice that one comment from that answer says, "Your usage of splat is nasty. Better looking option is `[*1..10]`." – Kache Sep 13 '20 at 15:00