Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the * (star) mean in Ruby? [duplicate]

Tags:

ruby

splat

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"} 
like image 354
Ernest Avatar asked Nov 12 '10 23:11

Ernest


People also ask

What does Star mean in Ruby?

A ruby is considered a Star Ruby when a three-point or six-point asterism, or star if you will, appears within the stone. This star is created when tiny fibers of rutile, also known as “silk,” have light reflected off of them in such a way that a star shape is formed.

What does Asterisk do in Ruby?

The * is the splat operator. It expands an Array into a list of arguments, in this case a list of arguments to the Hash. [] method. (To be more precise, it expands any object that responds to to_ary / to_a , or to_a in Ruby 1.9.)

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

What does '?' Mean in Ruby?

i know that the '?' in ruby is something that checks the yes/no fulfillment.


1 Answers

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.

like image 134
osgx Avatar answered Sep 30 '22 21:09

osgx