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?
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?
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.
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.
I believe it's just a convention for things that are boolean. A bit like saying "IsValid".
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.
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?"
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".
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