将散列传递给函数(* args)及其含义

当使用如下成语时:

def func(*args)
# some code
end

在谷歌上搜索这个具体的问题非常困难,我什么也找不到。

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

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

但我肯定还有更好的办法。

47521 次浏览

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

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

假设我们调用这个方法:

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

如果你现在检查 func2内的 arg1arg2other_args,你会得到以下结果:

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]将包含散列。

资源:


根据业务处的意见更新

如果要将 Hash 作为参数传递,则不应使用 splat 运算符。Ruby 允许您在方法调用中省略方括号 包括指定散列的(注意,请继续阅读)。因此:

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

相当于

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

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!).

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

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