yu shirota
yu shirota

Reputation: 127

How to use an argument with question mark in methods have keyword arguments

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

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

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

John
John

Reputation: 10069

Update

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)

Update 2

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

Related Questions