32

Possible Duplicate:
What is the * operator doing to this string in Ruby

Probably there is answer for that elsewhere, but I just don't know how to find it...

If I am right, the * means multiple parameters if used in function definition:

def hero(name, *super_powers)

But what does * do in the code like this:

Hash[*[[:first_name, 'Shane'], [:last_name, 'Harvie']].flatten] # => {:first_name=>"Shane", :last_name=>"Harvie"}
Community
  • 1
  • 1
Ernest
  • 8,701
  • 5
  • 40
  • 51

1 Answers1

66

Variable Length Argument List, Asterisk Operator

The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.

osgx
  • 90,338
  • 53
  • 357
  • 513
  • 2
    Also called the Variadic function – go minimal Nov 12 '10 at 23:58
  • 5
    Not a complete explanation. It is called the splat operator http://theplana.wordpress.com/2007/03/03/ruby-idioms-the-splat-operator/ – Ed S. Nov 13 '10 at 00:01
  • 1
    It looks like when it is followed by a &block it doesn't have to be the last parameter of a method. I came across this with the resources function on rails route mapping. I'm new to ruby and maybe that's more because the &block parameter is a special case. – DustinA Apr 07 '17 at 20:05