Innate abilities of objects

Ruby classes automatically inherit from the Object class and acquire several useful methods.

class Person
end

bob = Person.new
p bob.methods.sort

The bob object has access to a lot of methods because the Person object inherits from the Object class. The ancestors method demonstrates the inheritance chain of the Person object.

p Person.ancestors

The object_id method returns a number that is associated with an object and can be used for comparison. The following code demonstrates the object ids for some string objects and integer objects.

>> "matt".object_id
=> 70184007016960
>> "matt".object_id
=> 70184006991440
>> 100.object_id
=> 201
>> 100.object_id
=> 201

Interestingly, the object id for the two “matt” objects are different, but the object id for the 100 object is the same. For performance reasons, Integer objects only have one instance per number, so the object id is always the same. There can be multiple instances of strings, even if they have the same content, so the object ids will be different.

respond_to? is a predicate method that return true if the object can successfully respond to a message and false otherwise. The following example demonstrates how a generic object responds to the class method, but does not respond to the say_hello method.

>> obj = Object.new
>> obj.respond_to?(:class)
=> true
>> obj.respond_to?(:say_hello)
=> false

If the say_hello method is defined, then obj will respond to it.

>> def obj.say_hello; end
>> obj.respond_to?(:say_hello)
=> true

The send method is another acquired method that is useful for passing messages to objects. The following example demonstrates how dot notation and the send method can be used to pass the :class message to a generic object.

>> o = Object.new
=> #<Object:0x007fa9f9852d98>
>> o.class
=> Object
>> o.send(:class)
=> Object

Dot notation is typically used to send messages to objects, but the send method is a powerful alternative, especially when messages need to be passed to access the private methods of an object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s