I found that the expression [*1..4] returns the same as if I would do a (1..4).to_a, but I don't understand the syntax here. My understanding is that * is - being a unary operator in this case - to be the splat operator, and to the right of it, we have a Range. However, if just write the expression *1..4, this is a syntax error, and *(1..4) is a syntax error too. Why does the first [*1..4] work and how it is understood in detail?
How is the splat operator understood when applied to a range expression?
128 views Asked by user1934428 At
1
The splat
*converts the object to an list of values (usually an argument list) by calling itsto_amethod, so*1..4is equivalent to:On its own, the above isn't valid. But wrapped within square brackets,
[*1..4]becomes:Which is valid.
You could also write
a = *1..4which is equivalent to:Here, the list of values becomes an array due to Ruby's implicit array assignment.