简体   繁体   English

是否可以在 function 中同时为所有参数指定默认值?

[英]Is it possible to specify a default value for all parameters simultaneously in a function?

If I have a function like this:如果我有这样的 function:

def foo(a="this", b="this", c="this")
end

Is there some option to set a default value for all of them at the same time?是否有一些选项可以同时为所有这些设置默认值? Something like:就像是:

def foo(DEFAULT="this", a, b, c)
end

Metaprogramming Local Variables元编程局部变量

If you're trying to create positional method-local variables that can be overridden, you can use a bit of metaprogramming using the current Binding .如果您尝试创建可以被覆盖的位置方法局部变量,您可以使用当前的Binding进行一些元编程。 For example:例如:

def foo a=nil, b=nil, c=nil
  %i[a b c].map do |v|
    binding.local_variable_get(v) ||
    binding.local_variable_set(v, "this")
  end
  [a, b, c]
end

This will do what you seem to want.这将做你似乎想要的。 For example:例如:

foo 1
#=> [1, "this", "this"]

foo 1, 2
#=> [1, 2, "this"]

Other Approaches其他方法

Other approaches may include the deprecated use of options hashes with:其他方法可能包括不推荐使用选项哈希:

  • an options hash using Hash.new("this") in the method signature在方法签名中使用Hash.new("this")的选项 hash
  • a Hash#default= defined inside the body of the method在方法体内定义的Hash#default=
  • the use of Hash#fetch to return a default value when reading your options hash读取选项时使用Hash#fetch返回默认值 hash

If your goal is just to DRY up your code, it may be better to consider keyword arguments (eg def foo **kwargs ) rather than positional arguments, but your mileage may vary.如果您的目标只是干燥您的代码,最好考虑关键字 arguments (例如def foo **kwargs )而不是位置 arguments,但您的里程可能会有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM