Search code examples
rubysyntaxsplat

What's the feature in Ruby that allows "p *1..10" to print out the numbers 1-10?


require 'pp'

p *1..10

This prints out 1-10. Why is this so concise? And what else can you do with it?


Solution

  • It is "the splat" operator. It can be used to explode arrays and ranges and collect values during assignment.

    Here the values in an assignment are collected:

    a, *b = 1,2,3,4
    
    => a = 1
       b = [2,3,4]
    

    In this example the values in the inner array (the [3,4] one) is exploded and collected to the containing array:

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

    You can define functions that collect arguments into an array:

    def foo(*args)
      p args
    end
    
    foo(1,2,"three",4)
    
    => [1,2,"three",4]