Splatter that Array

February 23rd, 2007

This something fairly new to me, although I’ve seen it used by Ruby Guru’s – the splat operator *.

From my understanding, the splat operator takes an array and pulls the contents out of the array. It takes one argument and then takes that array and pulls the contents out. It’s still a bit confusing to me on some aspects, but here are a few examples to help simplify it:

Often times, we might do the following:
1
2
3
4
5
6
  why = [:lucky, :stiff, :with, :chunky, :bacon]
  v1 = why[0]
  v2 = why[1]
  v3 = why[2]
  v4 = why[3]
  v5 = why[4]

That is so verbose! With the splat, we can do this:

1
2
  why = [:lucky, :stiff, :with, :chunky, :bacon]
  v1,v2,v3,v4,v5 = *why

That two liner will do the same as the above code, only much shorter. If there were 6 elements in the array, and you only assigned 5 variables using the splat operator, only the first 5 would be assigned.

It also works going backwards:


  *why = "lucky", "stiff", "with", "chunky", "bacon"

That snip will then become an array with those string variables.

I’m sure there is much more cool things you can do with the splat operator than these trivial examples. Play around with, test it out and let me know what you learn.

3 Responses to “Splatter that Array”

  1. Tobi Says:

    Tanks, so it’s similar to the ‘list’ operator in PHP?

    list( $v1,$v2,$v3,$v4,$v5 ) = array( .....)
  2. shaug Says:

    Both of your examples work w/o the splatter operator:

    irb(main):001:0> why = [:lucky, :stiff, :with, :chunky, :bacon] => [:lucky, :stiff, :with, :chunky, :bacon] irb(main):002:0> v1,v2,v3,v4,v5 = why => [:lucky, :stiff, :with, :chunky, :bacon] irb(main):003:0> v1 => :lucky irb(main):004:0> v2 => :stiff irb(main):005:0> v3 => :with irb(main):006:0> v4 => :chunky irb(main):007:0> v5 => :bacon irb(main):008:0> why = "lucky", "stiff", "with", "chunky", "bacon" => ["lucky", "stiff", "with", "chunky", "bacon"] irb(main):009:0> why => ["lucky", "stiff", "with", "chunky", "bacon"]
  3. shaug Says:

    Now, w/better formatting:

    
    irb(main):001:0> why = [:lucky, :stiff, :with, :chunky, :bacon]
    => [:lucky, :stiff, :with, :chunky, :bacon]
    irb(main):002:0> v1,v2,v3,v4,v5 = why
    => [:lucky, :stiff, :with, :chunky, :bacon]
    irb(main):003:0> v1
    => :lucky
    irb(main):004:0> v2
    => :stiff
    irb(main):005:0> v3
    => :with
    irb(main):006:0> v4
    => :chunky
    irb(main):007:0> v5
    => :bacon
    irb(main):008:0> why = "lucky", "stiff", "with", "chunky", "bacon" 
    => ["lucky", "stiff", "with", "chunky", "bacon"]
    irb(main):009:0> why
    => ["lucky", "stiff", "with", "chunky", "bacon"]
    

Sorry, comments are closed for this article.