*(星号)符号在函数参数附近起什么作用,以及在其他情况下如何使用? [英] What does the * (asterisk) symbol do near a function argument and how to use that in others scenarios?

查看:99
本文介绍了*(星号)符号在函数参数附近起什么作用,以及在其他情况下如何使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

这篇关于*(星号)符号在函数参数附近起什么作用,以及在其他情况下如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆