Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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...

question from:https://stackoverflow.com/questions/1729284/ruby-what-does-the-asterisk-in-p-1-10-mean

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's the splat operator. You'll often see it used to split an array into parameters to a function.

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

my_values = [2, 3, 5]

my_function(*my_values) # returns 10

More commonly it is used to accept an arbitrary number of arguments

def my_other_function(to_add, *other_args)
  other_args.map { |arg| arg + to_add }
end

my_other_function(1, 6, 7, 8) # returns [7, 8, 9]

It also works for multiple assignment (although both of these statements will work without the splat):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...