如何同时使用 splat 和可选散列在 ruby 中定义方法? [英] How to define a method in ruby using splat and an optional hash at the same time?
问题描述
我可以定义这样的方法:
I am able to define a method like this:
def test(id, *ary, hash_params)
# Do stuff here
end
但这使得 hash_params
参数成为强制性的.这些也不起作用:
But this makes the hash_params
argument mandatory. These don't work either:
def t(id, *ary, hash_params=nil) # SyntaxError: unexpected '=', expecting ')'
def t(id, *ary, hash_params={}) # SyntaxError: unexpected '=', expecting ')'
有没有办法让它成为可选的?
Is there a way to make it optional?
推荐答案
你不能那样做.您必须考虑 Ruby 如何能够确定哪些属于 *ary
以及哪些属于可选散列.由于 Ruby 无法读懂您的想法,因此上面的参数组合(splat + optional)是无法逻辑解决的.
You can't do that. You have to think about how Ruby would be able to determine what belongs to *ary
and what belongs to the optional hash. Since Ruby can't read your mind, the above argument combination (splat + optional) is impossible for it to solve logically.
你要么必须重新排列你的论点:
You either have to rearrange your arguments:
def test(id, h, *a)
在这种情况下 h
将不是可选的.或者然后手动编程:
In which case h
will not be optional. Or then program it manually:
def test(id, *a)
h = a.last.is_a?(Hash) ? a.pop : nil
# ^^ Or whatever rule you see as appropriate to determine if h
# should be assigned a value or not.
这篇关于如何同时使用 splat 和可选散列在 ruby 中定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!