What is the purpose of the question mark operator in Ruby?
Sometimes it appears like this:
assert !product.valid?
sometimes it's in an if
construct.
This question is related to
ruby
It's also a common convention to use with the first argument of the test method from Kernel#test
irb(main):001:0> test ?d, "/dev" # directory exists?
=> true
irb(main):002:0> test ?-, "/etc/hosts", "/etc/hosts" # are the files identical
=> true
as seen in this question here
Also note ?
along with a character, will return the ASCII character code for A
For example:
?F # => will return 70
Alternately in ruby 1.8 you can do:
"F"[0]
or in ruby 1.9:
"F".ord
Also notice that ?F
will return the string "F"
, so in order to make the code shorter, you can also use ?F.ord
in Ruby 1.9 to get the same result as "F".ord
.
I believe it's just a convention for things that are boolean. A bit like saying "IsValid
".
In your example it's just part of the method name. In Ruby you can also use exclamation points in method names!
Another example of question marks in Ruby would be the ternary operator.
customerName == "Fred" ? "Hello Fred" : "Who are you?"
In your example
product.valid?
Is actually a function call and calls a function named valid?
. Certain types of "test for condition"/boolean functions have a question mark as part of the function name by convention.
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
It may be worth pointing out that ?
s are only allowed in method names, not variables. In the process of learning Ruby, I assumed that ?
designated a boolean return type so I tried adding them to flag variables, leading to errors. This led to me erroneously believing for a while that there was some special syntax involving ?
s.
Relevant: Why can't a variable name end with `?` while a method name can?
It's also used in regular expressions, meaning "at most one repetition of the preceding character"
for example the regular expression /hey?/
matches with the strings "he
" and "hey
".
Source: Stackoverflow.com