函数参数附近的 *(星号)符号有什么作用以及如何在其他场景中使用它?
我正在使用 Ruby on Rails 3,我想知道函数参数附近存在 *
运算符意味着什么,并了解它在其他场景中的用法。
示例场景(此方法来自 Ruby on Rails 3 框架):
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
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.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 splat 运算符,它来自 ruby(因此不是特定于 Rails 的)。根据其使用位置,它可以通过两种方式应用:
在您的函数中,您会看到函数定义中使用的 splat 运算符。结果是该函数接受任意数量的参数。完整的参数列表将作为数组放入
args
中。第二种变体是当您考虑以下方法时:
它只需要三个参数。现在,您可以像下面这样调用此方法。
在本例中应用于数组的 splat 会将其拆分,并将数组的每个元素作为单独的参数传递给该方法。您甚至可以通过调用 foo 来执行相同的操作:
正如您在示例方法中所看到的,这些规则确实以相同的方式应用于块参数。
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:
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.The second variant would be when you consider the following method:
It requires exactly three arguments. You can now call this method like follows
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
:As you can see in your example method, these rules do apply to block parameters in the same way.
这是一个 splat 参数,这基本上意味着传递给该方法的任何“额外”参数都将分配给 *args。
This is a splat argument, which basically means that any 'extra' arguments passed to the method will all be assigned to *args.