views:

163

answers:

1

the line

p *1..10

does exactly the same thing as

(1..10).each { |x| puts x }

which gives you the following output:

$ ruby -e "p *1..10"
1
2
3
4
5
6
7
8
9
10

it's a great shortcut when working with textmate for example, but what does the asterisk do? how does that work? couldn't find anything on the net...

+12  A: 

It's the splat operator. Often times you see it used when you want to split up an array to use as parameters of a function.

def my_function(param1, param2, param3)
  param1 * param2 * param3
end

my_values = [2, 3, 5]

my_function(*my_values) # returns 30

Or for multiple assignment (it works both ways):

first, second, third = *my_values
*my_new_array = 7, 11, 13

For your example, these two would be equivalent:

p *1..10
p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Neall
i seems to me that a, b, c = *myvaluesis equivalent to a, b, c = myvaluesor is ruby implicitly using the splat operator in this case?
padde
@Patrick Yes, assignment where there is one object on one side and multiple objects on the other will sort of imply a splat operator. So that's not a very useful example, I guess.
Neall