1. Home
  2. Computing & Technology
  3. Ruby

What's New in Ruby 1.9.1? - -Multiple Splats in Ruby 1.9.1
Using More Than One Splat Operator

By , About.com Guide

The splat operator will flatten an array operator in an assignment or method call operation. For example, calling func( [1,2] ) will call the func method with a single array argument. Using the splat operator *, you can flatten that array into individual arguments. So calling func( *[1,2] ) will call the func method with the two individual arguments 1 and 2.

In Ruby 1.8, you could only use one splat operator in an assignment or method call, and it could only be the last argument in the list. For example, you could do this: func( 1, *[2,3] ) but not this: func( *[1,2], 3 ). Also, because of this, you could only use one splat operator per assignment or method call.

In Ruby 1.9, you can use any number of splat operators. Further, the splat operators can be anywhere in the assignment or argument list.

#!/usr/bin/env ruby

# This will work on both Ruby 1.8 and 1.9
a, b, c = *[1, 2], 3

# This will fail on 1.8, but work on 1.9
a, b, c = 1, *[2, 3]

# Even this will work on 1.9, but not 1.8
a, b, c, d, e, f = *[1, 2], 3, *[4, 5]
More Ruby Quick Tips
Explore Ruby
By Category
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Beginning Ruby
  5. New in Ruby 1.9.1
  6. Multiple Splats in Ruby 1.9.1

©2009 About.com, a part of The New York Times Company.

All rights reserved.