什么是*符号附近做一个函数的参数,以及如何使用,在别人的情景? [英] What does the * symbol do near a function argument and how to use that in others scenarios?

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

问题描述

我在Rails 3的使用Ruby,我想知道是什么意思一个的presence * 运营商附近的一个函数参数,并了解其用法在别人的情况。

示例场景(这个方法是从Ruby on Rails的3框架):

  DEF找到(*参数)
  返回to_a.find {| * block_args |产量(* block_args)}如果block_given?  选项​​= args.extract_options!  如果选项。present?
    apply_finder_options(选项).find(*参数)
  其他
    案例args.first
    时:第一,:最后:所有
      发送(args.first)
    其他
      find_with_ids(*参数)
    结束
  结束
结束


解决方案

这是运营商图示,它来自红宝石(因此是不特定轨)。它可以两种方式取决于它被使用的地方可以应用


  • 要包等多项参数到一个数组

  • 要阵列分裂成一个参数列表

在你的函数,你会看到在函数定义中使用的图示运营商。其结果是,该函数接受任何数量的参数。完整的参数列表将被放入 ARGS 作为数组。

 高清美孚(*参数)
  args.each_with_index {| ARG,我|把#{I + 1}#{ARG}
结束富(一,B,C)
#1,A< ==这是输出
#2。B
#3,Ç

当你考虑下面的方法的第二个变量是:

  DEF条(A,B,C)
  A + B + C
结束

这正是需要三个参数。现在,您可以调用此方法如下一样

  my_array = [1,2,3]
酒吧(* my_array)
#6回报

在这种情况下,应用到阵列中的图示会分裂它和数组的每个元素传递作为一个单独的参数的方法。你甚至可以通过调用做同样的

 美孚(* my_array)
#1,1其中p ==这是输出
#2 2
#3 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.

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

解决方案

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:

  • to "pack" a number of arguments into an array
  • to split up an array into an argument list

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

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天全站免登陆