How to pass "extra" keyword arguments to a lambda?

Viewed 37

There is this code:

a = -> (var:) { "Var: #{var}" }

It works successfully when used like this:

a.call(var: "Hi!")

But how can I pass arguments to .call that might not be used?

a.call(var: "Hi!", extra: "")

ArgumentError (unknown keyword: :extra)

For example, I want to decide in different places whether I need to use certain variables in texts.


I have a root location where all named arguments are always passed to .call. And I need to pass lambda in other places, where only the necessary arguments are described.

1 Answers

You can choose only the args you're interested in inside the proc, and ignore the others by using "splatted" keyword arguments:

a = ->(**kwargs){ "Var #{kwargs[:var]}" }

a.call(var: "foo") #=> "Var foo"

a.call(var: "foo", extra: "bar") #=> "Var foo"

Is that what you're looking for?

Related