ruby:"p*1..10"中的星号是什么意思

Pat*_*ity 37 ruby operators range

这条线

p *1..10
Run Code Online (Sandbox Code Playgroud)

完全一样的事情

(1..10).each { |x| puts x }
Run Code Online (Sandbox Code Playgroud)

它给你以下输出:

$ ruby -e "p *1..10"
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)

例如,与textmate合作时,这是一个很好的捷径,但是星号是做什么的?这是如何运作的?在网上找不到任何东西......

Nea*_*all 61

这是splat运营商.您经常会看到它用于将数组拆分为函数的参数.

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

my_values = [2, 3, 5]

my_function(*my_values) # returns 10
Run Code Online (Sandbox Code Playgroud)

更常见的是,它用于接受任意数量的参数

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]
Run Code Online (Sandbox Code Playgroud)

它也适用于多个赋值(尽管这两个语句都可以在没有splat的情况下工作):

first, second, third = *my_values
*my_new_array = 7, 11, 13
Run Code Online (Sandbox Code Playgroud)

对于您的示例,这两个是等效的:

p *1..10
p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Run Code Online (Sandbox Code Playgroud)