将哈希值传递给函数 ( *args ) 及其含义 [英] Passing a hash to a function ( *args ) and its meaning

查看:50
本文介绍了将哈希值传递给函数 ( *args ) 及其含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用成语时,例如:

def func(*args)
  # some code
end

*args 是什么意思?谷歌搜索这个特定问题非常困难,我找不到任何东西.

What is the meaning of *args? Googling this specific question was pretty hard, and I couldn't find anything.

似乎所有参数实际上都出现在 args[0] 中,所以我发现自己编写了防御性代码,例如:

It seems all the arguments actually appear in args[0] so I find myself writing defensive code such as:

my_var = args[0].delete(:var_name) if args[0]

但我确定我错过了更好的方法.

But I'm sure there's a better way I'm missing out on.

推荐答案

*splat(或星号)运算符.在方法的上下文中,它指定一个可变长度的参数列表.在您的情况下,传递给 func 的所有参数都将放入一个名为 args 的数组中.您还可以在可变长度参数之前指定特定参数,如下所示:

The * is the splat (or asterisk) operator. In the context of a method, it specifies a variable length argument list. In your case, all arguments passed to func will be putting into an array called args. You could also specify specific arguments before a variable-length argument like so:

def func2(arg1, arg2, *other_args)
  # ...
end

假设我们调用这个方法:

Let's say we call this method:

func2(1, 2, 3, 4, 5)

如果您现在检查 func2 中的 arg1arg2other_args,您将得到以下结果:

If you inspect arg1, arg2 and other_args within func2 now, you will get the following results:

def func2(arg1, arg2, *other_args)
  p arg1.inspect       # => 1
  p arg2.inspect       # => 2
  p other_args.inspect # => [3, 4, 5]
end

在您的情况下,您似乎将散列作为参数传递给您的 func,在这种情况下,args[0] 将包含散列,因为您正在观察.

In your case, you seem to be passing a hash as an argument to your func, in which case, args[0] will contain the hash, as you are observing.

资源:

根据 OP 的评论进行更新

如果您想将 Hash 作为参数传递,则不应使用 splat 运算符.Ruby 允许您在方法调用中省略方括号,包括那些指定哈希值(有警告,请继续阅读).因此:

If you want to pass a Hash as an argument, you should not use the splat operator. Ruby lets you omit brackets, including those that specify a Hash (with a caveat, keep reading), in your method calls. Therefore:

my_func arg1, arg2, :html_arg => value, :html_arg2 => value2

相当于

my_func(arg1, arg2, {:html_arg => value, :html_arg2 => value2})

当 Ruby 在您的参数列表中看到 => 运算符时,它知道将参数作为哈希,即使没有显式的 {...} 表示法(请注意,这仅适用于哈希参数是最后一个!).

When Ruby sees the => operator in your argument list, it knows to take the argument as a Hash, even without the explicit {...} notation (note that this only applies if the hash argument is the last one!).

如果你想收集这个散列,你不需要做任何特别的事情(尽管你可能想在你的方法定义中指定一个空散列作为默认值):

If you want to collect this hash, you don't have to do anything special (though you probably will want to specify an empty hash as the default value in your method definition):

def my_func(arg1, arg2, html_args = {})
  # ...
end

这篇关于将哈希值传递给函数 ( *args ) 及其含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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