How can I collapse double splat arguments?

The splat extension of an empty array in a method call effectively reduces the argument to zero (empty brackets are added for clarity):

def foo() end def bar(*args) foo(*args) end bar(1) # ArgumentError, as expected bar() # works 

But the same does not apply to the hashing argument:

 def baz() end def qux(**opts) baz(**opts) end qux # ArgumentError, **opts becomes {} 

I can get around this by explicitly checking for an empty hash:

 def quux(callable, **opts) if opts.empty? callable.() else callable.(**opts) end end c = ->{} quux(c) # works 

But is there a better / better way to do this, or is there a change planned for this behavior? I do not know the signatures of foo and baz when writing bar and qux , since the latter are part of the factory constructor shell.

+4
source share
1 answer

Try the following:

 def baz() end def qux(**opts) baz(*opts) end qux 

To learn more about how a hash works, follow these steps:

 h = {} puts h # {} puts *h # nothing output puts **h #{} 
0
source

Source: https://habr.com/ru/post/1211352/


All Articles