我可以定义这样的方法:
def test(id, *ary, hash_params)
# Do stuff here
end
但这使得hash_params
参数强制。这些也不起作用:
def t(id, *ary, hash_params=nil) # SyntaxError: unexpected '=', expecting ')'
def t(id, *ary, hash_params={}) # SyntaxError: unexpected '=', expecting ')'
有没有办法让它成为可选的?
ActiveSupport 通过使用数组扩展对此提供支持extract_options!
.
def test(*args)
opts = args.extract_options!
end
如果最后一个元素是哈希,那么它将从数组中弹出并返回它,否则它将返回一个空哈希,这在技术上与你想要的相同(*args, opts={})
to do.
ActiveSupport 数组#extract_options!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)