问题描述
我正在使用 Ruby on Rails 3,我想知道在函数参数附近存在 *
运算符意味着什么,并了解它在其他场景中的用法.
I am using Ruby on Rails 3 and I would like to know what means the presence of a *
operator near a function argument and to understand its usages in others scenarios.
示例场景(此方法来自 Ruby on Rails 3 框架):
Example scenario (this method was from the Ruby on Rails 3 framework):
def find(*args)
return to_a.find { |*block_args| yield(*block_args) } if block_given?
options = args.extract_options!
if options.present?
apply_finder_options(options).find(*args)
else
case args.first
when :first, :last, :all
send(args.first)
else
find_with_ids(*args)
end
end
end
推荐答案
这是 splat 运算符,它来自 ruby(因此不是特定于 rails 的).根据使用地点的不同,它可以通过两种方式应用:
This is the splat operator, which comes from ruby (and is thus not rails specific). It can be applied in two ways depending on where it is used:
- 将多个参数打包"到一个数组中
- 将数组拆分为参数列表
在您的函数中,您会看到函数定义中使用的 splat 运算符.结果是该函数接受任意数量的参数.完整的参数列表将作为数组放入args
.
In your function, you see the splat operator used in the function definition. The result is that the function accepts any number of arguments. The complete argument list will be put into args
as an array.
def foo(*args)
args.each_with_index{ |arg, i| puts "#{i+1}. #{arg}" }
end
foo("a", "b", "c")
# 1. a <== this is the output
# 2. b
# 3. c
第二种变体是当您考虑以下方法时:
The second variant would be when you consider the following method:
def bar(a, b, c)
a + b + c
end
它正好需要三个参数.你现在可以像下面这样调用这个方法
It requires exactly three arguments. You can now call this method like follows
my_array = [1, 2, 3]
bar(*my_array)
# returns 6
在这种情况下应用于数组的 splat 将拆分它并将数组的每个元素作为单独的参数传递给方法.你甚至可以通过调用 foo
:
The splat applied in this case to the array will split it and pass each element of the array as an individual parameter to the method. You could do the same even by calling foo
:
foo(*my_array)
# 1. 1 <== this is the output
# 2. 2
# 3. 3
正如您在示例方法中所见,这些规则确实以相同的方式应用于块参数.
As you can see in your example method, these rules do apply to block parameters in the same way.
这篇关于*(星号)符号在函数参数附近有什么作用以及如何在其他场景中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!