鉴于此方法定义:
def foo(a = nil, b: nil)
p a: a, b: b
end
当我使用单个哈希参数调用该方法时,哈希总是隐式转换为关键字参数,无论**
:
hash = {b: 1}
foo(hash) #=> {:a=>nil, :b=>1}
foo(**hash) #=> {:a=>nil, :b=>1}
我可以传递另一个(空)哈希作为解决方法:
foo(hash, {}) #=> {:a=>{:b=>1}, :b=>nil}
But,这看起来相当麻烦和尴尬。
我希望 Ruby 能够像处理数组一样处理这个问题,即:
foo(hash) #=> {:a=>{:b=>1}, :b=>nil}
foo(**hash) #=> {:a=>nil, :b=>1}
并使用文字:
foo({b: 1}) #=> {:a=>{:b=>1}, :b=>nil}
foo(b: 1) #=> {:a=>nil, :b=>1}
foo(**{b: 1}) #=> {:a=>nil, :b=>1}
当前的实现看起来像是一个缺陷,而我期望它的工作方式似乎是显而易见的。
这是一个被忽视的边缘情况吗?我不这么认为。没有以这种方式实施可能有充分的理由。
有人可以启发我吗?