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).

Share

  • Facebook
  • Twitter
  • HackerNews
  • Reddit
  • Tumblr
  • Delicious
  • Email
  • RSS

No related posts.

About Eric Davis

I founded Little Stream Software where I provide Redmine and ChiliProject services to help projects teams. I also created an ebook, Redmine Tips, were I show you how to become more productive using Redmine. I am also the author of Refactoring Redmine, where I go about refactoring Rails using Redmine as an example.

Chirk HR     Reuse your existing job applicants »
WP Socializer Aakash Web