如何将双splat参数折叠成什么?

时间:2015-01-07 14:16:24

标签: ruby syntax

在方法调用中展开空数组有效地将参数减少为空(为清晰起见添加了空括号):

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

但有没有更好/更好的方法来做到这一点,或者是否计划改变这种行为?在编写foobaz时,我不知道barqux的签名,因为后者是工厂式构造函数包装器的一部分。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

def baz()
end

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

qux

要了解有关* hash如何工作的更多信息,请尝试以下方法:

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