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

2019-03-09 07:04发布

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条回答
做自己的国王
2楼-- · 2019-03-09 07:58

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
查看更多
登录 后发表回答