*(星级)在Ruby中意味着什么? [重复]

时间:2021-09-13 22:28:34

Possible Duplicate:
What is the * operator doing to this string in Ruby

可能重复:*运算符在Ruby中对此字符串执行的操作是什么

Probably there is answer for that elsewhere, but I just don't know how to find it...

可能在其他地方有答案,但我只是不知道如何找到它...

If I am right, the * means multiple parameters if used in function definition:

如果我是对的,*表示在函数定义中使用的多个参数:

def hero(name, *super_powers)

But what does * do in the code like this:

但是*在代码中做了什么:

Hash[*[[:first_name, 'Shane'], [:last_name, 'Harvie']].flatten] # => {:first_name=>"Shane", :last_name=>"Harvie"}

1 个解决方案

#1


39  

Variable Length Argument List, Asterisk Operator

可变长度参数列表,星号运算符

The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

方法的最后一个参数可以在前面加上星号(*),有时也称为“splat”运算符。这表示可以将更多参数传递给函数。收集这些参数并创建一个数组。

The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.

星号运算符也可以在方法调用中的Array参数之前。在这种情况下,将展开数组并传入值,就好像它们用逗号分隔一样。

#1


39  

Variable Length Argument List, Asterisk Operator

可变长度参数列表,星号运算符

The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

方法的最后一个参数可以在前面加上星号(*),有时也称为“splat”运算符。这表示可以将更多参数传递给函数。收集这些参数并创建一个数组。

The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.

星号运算符也可以在方法调用中的Array参数之前。在这种情况下,将展开数组并传入值,就好像它们用逗号分隔一样。