如何使用图示和可选的散列同时以限定在红宝石的方法? [英] 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如何能够确定哪些属于 *元
,哪些属于可选的哈希值。由于红宝石无法了解你的心思,上面的参数组合(图示+可选)是不可能为它在逻辑上解决。
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.
这篇关于如何使用图示和可选的散列同时以限定在红宝石的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!