Reputation: 21
In Ruby, what is the difference of using "?" inside if condition?
if object.property
or
if object.property?
I found the usage of both of them in a method, without understanding the difference
Thanks a lot
Upvotes: 2
Views: 111
Reputation: 369624
In Ruby, foo.bar
is the syntax for a message send. It will first evaluate the expression foo
(which is either dereferencing a local variable or a receiverless message send to the implicit receiver self
) and then send the message bar
to the resulting object.
Once you know what message send in Ruby looks like, it is easy to see what object.property?
does: It will first evaluate the expression object
(which is either dereferencing a local variable or a receiverless message send to the implicit receiver self
) and then send the message property?
to the resulting object.
So, what is the difference between the two? Well, the first one sends the message property
and the second one sends the message property?
. This is no different than if the first one had been object.foo
and the second one had been object.bar
.
Method names ending in ?
are typically used for predicate methods, i.e. for methods that ask a "Yes/No" question. A good example is Numeric#zero?
.
Upvotes: -1
Reputation: 26294
?
can be part of the function name. It is not a special operator if it comes at the end of a method name. Also !
can be part of the method name too. So what that line is doing is calling both object.property
and object.property?
methods.
What are the restrictions for method names in Ruby?
Upvotes: 5