Simone D'Onofrio
Simone D'Onofrio

Reputation: 21

Ruby: usage of ? in if condition

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

Answers (2)

Jörg W Mittag
Jörg W Mittag

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

Chloe
Chloe

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

Related Questions