Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

People also ask

WHAT A at the end of a method name means in Ruby?

In Ruby the ? means that the method is going to return a boolean and the ! modifies the object it was called on.

What is method name in Ruby?

Ruby allows method names and other identifiers to contain such characters.) Method names may contain letters, numbers, an _ (underscore or low line) or a character with the eight bit set. Method names may end with a ! (bang or exclamation mark), a ? (question mark) or = equals sign.

What happens when you call a method in Ruby?

5-7: using "method" and "call" method(:hello) returns an instance of Method class. This object can be passed around as any value and can be called any time - it also stores the reference to the object to which it belongs, so if I change the user's name, the new one will be used: method = user.

What does :+ mean in Ruby?

inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.


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


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

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.


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