Ruby’s Array splat operator (*array)

I’ve had some people tell me that they didn’t know about the splat operator in Ruby (*array) so here’s a quick example of how it’s used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>> array = [:a, :b, :c]
[
    [0] :a,
    [1] :b,
    [2] :c
]
>> a, b, c = *array
[
    [0] :a,
    [1] :b,
    [2] :c
]
>> a
:a
>> b
:b
>> c
:c

It splits the elements of the array into single items which are returned as a group (I think they are called parameters). So in second statement in the example above:

  • a gets the first element of array, :a
  • b gets the second element of array, :b
  • c gets the third element of array, :c

This is commonly used to set a bunch of variables or when working with a method’s arguments (e.g. in a monkey patch).

2 comments

  1. M.T.MAHARAJAN says:

    teach me an array.
    how you create a array &&
    how you create a array +
    how you create a array *
    how you create a array ==
    how you create a array .

  2. Raf Magana says:

    In this particular example you don’t need to splat operator, this should work the same way with or without it:

    array = [:a, :b, :c]
    a, b, c = array

    a # => :a
    b # => :b
    c # => :c

Comments are closed.