Splat扩展方法调用中的空数组可有效地将参数减少为空(为清楚起见添加了空括号):
def foo()
end
def bar(*args)
foo(*args)
end
bar(1) # ArgumentError, as expected
bar() # works
Run Code Online (Sandbox Code Playgroud)
但这不适用于哈希参数:
def baz()
end
def qux(**opts)
baz(**opts)
end
qux # ArgumentError, **opts becomes {}
Run Code Online (Sandbox Code Playgroud)
我可以通过显式检查空哈希来解决此问题:
def quux(callable, **opts)
if opts.empty?
callable.()
else
callable.(**opts)
end
end
c = ->{}
quux(c) # works
Run Code Online (Sandbox Code Playgroud)
但是,是否有更好/更精细的方法来执行此操作,或者计划对此行为进行更改?我不知道foo以及baz何时编写barand 的签名qux,因为后者是工厂式构造函数包装器的一部分。