tags:

views:

1285

answers:

7
+9  Q: 

Ruby question mark

Hi I am new to Ruby and I am trying to learn Rails. I do not understand the use of the question mark (?) in Ruby.

Sometimes appears like this:

assert !product.valid?

sometimes I saw it in an if construct.

Could you tell me its meaning?

+14  A: 

It is a code style convention; it indicates that a method returns a boolean value.

The question mark is a valid character to end a method name with.

chillitom
+7  A: 

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.

Eifion
A: 

I believe it's just a convention for things that are boolean. A bit like saying "IsValid".

Neil Barnwell
A: 

In your example

product.valid?

Is actually a function call and call a function called valid? Certain types of 'test for condition'/boolean functions have a question mark as part of the function name by convention.

Timo Geusch
answer.gsub!(/function/, 'method')
glenn jackman
Good comment… lolz
Jonathan Sterling
+8  A: 

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?"
Andy Gaskell
To expand on Andy's answer you will also see things like: customerName == user.logged_in? ? user.name : "Who are you?" Note the double question mark
Question Mark
A: 

It's also used in regular expressions, meanning "at most one repetition of the preceding character"

for example the regular expression /hey?/ matches with the strings "he" and "hey".

José Joel.
+4  A: 

Also note ? along with a character, will return the ASCII character code for A

For eg;

?F # => will return 70

Alternately in ruby 1.8 you can do

"F"[0]

or in ruby 1.9

"F".ord
Greg Osuri
Interesting, thanks
rtacconi
In ruby 1.9 it will return `'F'`
klew