繁体   English   中英

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

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

如果我有这样的 function:

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

是否有一些选项可以同时为所有这些设置默认值? 就像是:

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

元编程局部变量

如果您尝试创建可以被覆盖的位置方法局部变量,您可以使用当前的Binding进行一些元编程。 例如:

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

这将做你似乎想要的。 例如:

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

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

其他方法

其他方法可能包括不推荐使用选项哈希:

  • 在方法签名中使用Hash.new("this")的选项 hash
  • 在方法体内定义的Hash#default=
  • 读取选项时使用Hash#fetch返回默认值 hash

如果您的目标只是干燥您的代码,最好考虑关键字 arguments (例如def foo **kwargs )而不是位置 arguments,但您的里程可能会有所不同。

暂无
暂无

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

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