在方法调用中展开空数组有效地将参数减少为空(为清晰起见添加了空括号):
def foo()
end
def bar(*args)
foo(*args)
end
bar(1) # ArgumentError, as expected
bar() # works
但同样不适用于哈希参数:
def baz()
end
def qux(**opts)
baz(**opts)
end
qux # ArgumentError, **opts becomes {}
我可以通过显式检查空哈希来解决这个问题:
def quux(callable, **opts)
if opts.empty?
callable.()
else
callable.(**opts)
end
end
c = ->{}
quux(c) # works
但有没有更好/更好的方法来做到这一点,或者是否计划改变这种行为?在编写foo
和baz
时,我不知道bar
和qux
的签名,因为后者是工厂式构造函数包装器的一部分。
答案 0 :(得分:0)
尝试以下方法:
def baz()
end
def qux(**opts)
baz(*opts)
end
qux
要了解有关* hash如何工作的更多信息,请尝试以下方法:
h = {}
puts h # {}
puts *h # nothing output
puts **h #{}