Reputation: 127
How to use an argument with question mark in methods have keyword arguments?
def foo(arg?:)
p arg? # ERROR
end
foo(arg?: true)
Upvotes: 3
Views: 1837
Reputation: 230346
You can't do that. Parameter names can't have question or exclamation marks. Only method names can have them.
As John mentions, you should be able to use the good old options hash. Although, in this case foo(arg?: true)
, arg?: true
is a key-value pair in a hash, not a keyword argument. Big difference (with options hash, you don't get effortless required parameters and typo protection, for example).
Upvotes: 5
Reputation: 10069
Just confirmed it, you can do foo(arg?: true)
Original:
I'm not sure that you can have a "?" in a kwarg. You could try making the method have one input arg which is a hash, and then I think you could do
def foo(arg)
p arg[:"arg?"]
end
foo(:"arg?" => true)
The quotes may not be necessary, I'd have to open up the console to check. In which case:
foo(arg?: true)
Sergio has rightly called out the fact that I'm not using a key word argument (kwarg) in this solution, instead I'm passing a single, regular argument which I know needs to be a hash with a :arg?
key. This is commonly referred to as an options hash. This is what people did before the ruby language added support for kwargs (or so I'm told :).
Upvotes: 4