Ruby On Rails Lesson
Objects and Message Passing
Everything in Ruby, including strings and even nil, is an object. We’ll see the technical meaning of this in Section 4.4.2, but I don’t think anyone ever understood objects by reading the definition in a book; you have to build up your intuition for objects by seeing lots of examples.
It’s easier to describe what objects do, which is respond to messages. An object like a string, for example, can respond to the message length, which returns the number of characters in the string:
Typically, the messages that get passed to objects are methods, which are functions defined on those objects.4 Strings also respond to the empty? method:
Note the question mark at the end of the empty? method. This is a Ruby conventionindicating that the return value is boolean: true or false. Booleans are especially useful for control flow:
Booleans can also be combined using the && (‘‘and’’), || (‘‘or’’), and ! (‘‘not’’) operators:
Since everything in Ruby is an object, it follows that nil is an object, so it too can respond to methods. One example is the to_s method that can convert virtually any
object to a string:
This certainly appears to be an empty string, as we can verify by chaining the messages we pass to nil:
We see here that the nil object doesn’t itself respond to the empty? method, but nil.to_s does.
There’s a special method for testing for nil-ness, which you might be able to guess:
also shows an alternate use of the if keyword: Ruby allows you to write a statement that is evaluated only if the statement following if is true. There’s a complementary
unless keyword that works the same way: