1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

What's New in Ruby 1.9.1? --Multiple Splats in Ruby 1.9.1

Using More Than One Splat Operator

By

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]
 
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. New in Ruby 1.9.x
  6. Multiple Splats in Ruby 1.9.1

©2014 About.com. All rights reserved.