rubysplat

How is the splat operator understood when applied to a range expression?


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?


Solution

  • The splat * converts the object to an list of values (usually an argument list) by calling its to_a method, so *1..4 is equivalent to:

    1, 2, 3, 4
    

    On its own, the above isn't valid. But wrapped within square brackets, [*1..4] becomes:

    [1, 2, 3, 4]
    

    Which is valid.

    You could also write a = *1..4 which is equivalent to:

    a = 1, 2, 3, 4
    #=> [1, 2, 3, 4]
    

    Here, the list of values becomes an array due to Ruby's implicit array assignment.