What does the question mark at the end of a method name mean in Ruby?

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.


Solution 1:

It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value).

The question mark is a valid character at the end of a method name.

https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names

Solution 2:

Also note ? along with a character acts as shorthand for a single-character string literal since Ruby 1.9.

For example:

?F # => is the same as "F"

This is referenced near the bottom of the string literals section of the ruby docs:

There is also a character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that corresponds to a single codepoint in the script encoding:

?a       #=> "a"
?abc     #=> SyntaxError
?\n      #=> "\n"
?\s      #=> " "
?\\      #=> "\\"
?\u{41}  #=> "A"
?\C-a    #=> "\x01"
?\M-a    #=> "\xE1"
?\M-\C-a #=> "\x81"
?\C-\M-a #=> "\x81", same as above
?あ      #=> "あ"

Prior to Ruby 1.9, this returned the ASCII character code of the character. To get the old behavior in modern Ruby, you can use the #ord method:

?F.ord # => will return 70

Solution 3:

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.

Solution 4:

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?"