简体   繁体   English

Ruby自动将Hash扩展为关键字参数,而不需要双splat

[英]Ruby automatically expands Hash into keyword arguments without double splat

The below Ruby code results in: unknown keyword: a (ArgumentError) : 下面的Ruby代码导致: unknown keyword: a (ArgumentError)

def test(x={}, y: true); end

test({a:1})

Why? 为什么? I would expect this to happen with test(**{a:1}) , but I don't understand why my hash is being automagically expanded without the double splat. 我希望这会发生在test(**{a:1}) ,但我不明白为什么我的哈希是在没有双splat的情况下自动扩展的。

Since x is optional, hash moves over to kwarg argument. 由于x是可选的,因此hash转移到kwarg参数。 Unspecified keywords raise error in that case: 在这种情况下,未指定的关键字会引发错误:

def foo(name:)
  p name
end

foo # raises "ArgumentError: missing keyword: name" as expected
foo({name: 'Joe', age: 10}) # raises "ArgumentError: unknown keyword: age"

Check out this article 看看这篇文章

I'd also find it a bug as it behaves quite inconsistently, only for hashes with keys of Symbol type: 我也发现它是一个bug,因为它的行为非常不一致,只适用于带有Symbol类型键的哈希:

test({a:1})  # raises ArgumentError
test({'a' => 1})  # nil, properly assigned to optional argument x
method(:test).parameters
=> [[:opt, :x], [:key, :y]]

You may pass both arguments and it starts to assign them properly, but this is not a solution. 您可以传递两个参数并开始正确分配它们,但这不是解决方案。

test({a:1}, {y:false})  # nil

Any reason why this is not a bug but an expected behavior ? 有什么理由说这不是一个bug而是一个预期的行为?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM