裸星号作为方法定义中的参数:def f(*) [英] naked asterisk as parameter in method definition: def f(*)
问题描述
我知道这是什么意思
def f(*args)
...
end
但这是什么意思,为什么要使用它?它也可以与命名参数一起显示吗?
But what does this mean and why would you want to use it? Can it appear with named parameters, too?
def f(*)
...
end
推荐答案
def f(*)
与def f(*args)
具有相同的作用,不同之处在于它没有命名全局参数数组.如果希望函数接受任意数量的参数,但实际上不需要在函数中引用它们,则可以使用它-例如,如果要覆盖方法但调用super
而不传递显式参数列表,导致原始参数传递给super
.
def f(*)
has the same effect as def f(*args)
, except that it does not name the globbed argument array. You might use it if you want the function to accept any number of arguments but don't actually need to refer to them within the function -- for example, if you are overriding a method but calling super
without passing an explicit argument list, which results in the original arguments being passed to super
.
您也可以编写def f(a, b, *)
.
这篇关于裸星号作为方法定义中的参数:def f(*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!