Ruby automatically extends Hash to keyword arguments without double character

The following is the Ruby code unknown keyword: a (ArgumentError):

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

test({a:1})

Why? I expect this to happen with test(**{a:1}), but I do not understand why my hash automatically expands without a double character.

+4
source share
2 answers

Since x is optional, the hash goes to the kwarg argument. Undefined keywords cause an error in this 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"

Mark this article

+2
source

I would also find it a mistake, since it behaves completely inconsistently, only for hashes with keys like Symbol:

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

You can pass both arguments and start assigning them correctly, but this is not a solution.

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

Any reason why this is not an error but the expected behavior?

+1
source

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