Inspired by a StackOverflow question curious how correctly use
positional and named method/lambda/proc arguments.
Assume following method with both positional and named arguments
optional:
def meth(arg = {foo: 1}, kwarg: ‘bar’)
p arg, kwarg
end
Now I’d like to send meth with arg set to a different hash, kwarg leave
the default:
meth({foo:2})
ArgumentError: unknown keyword: foo
Surprisingly when hash argument has non-symbol key, it is taken as
positional as expected:
meth({‘foo’ = > 2})
{“foo”=>2}
“bar”
=> [{“foo”=>2}, “bar”]
By a trial-and-error I’ve figured out {foo: 2} can be “enforced” in
assignment to optional arg, when an extra empty hash is passed:
meth({foo:2},{})
{:foo=>2}
“bar”
=> [{:foo=>2}, “bar”]
Can somebody explain what’s going on here ?
Thanks.