ruby: what does the asterisk in “p *1..10” mean

吃可爱长大的小学妹 提交于 2019-12-03 04:09:39

问题


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


回答1:


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


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!