Monday, February 12, 2007

Spl*t and Parameters

I encountered a splat (*) in the context of a method call:

redirect_to *options

Apparently what this does is to use the contents of the array options as individual parameters in the call to the method redirect_to. So, if this is the signature for the redirect_to method:

def redirect_to(protocol, host, path)

Then array elements will be mapped to the parameters will be mapped as follows:

options[0] -> protocol
options[1] -> host
options[2] -> path

class Test
   def redirect_to(protocol, host, path)
      "#{protocol}://#{host}#{path}"
   end
end

Then, in irb, I can enter the following code:

t = Test.new
t.redirect_to *["https", "www.apple.com", "/macbook"]

... and see the following result:

=> "https://www.apple.com/macbook"

There is also a usage of the splat within the method signature which accumulates all excess parameters into an array:

class Test
   def splat_me (a, *the_rest)
      [a, the_rest]
   end
end

Then, in irb, I can enter the following code:

t = Test.new
t.splat_me 1, 2, 3, 4

... and see the following result:

=> [1, [2, 3, 4]]

No comments: