Friday, November 22, 2013

Whats there in an Object

Whats there in an Object


Lets start with the basics and look at the following piece of Ruby code:

 class A  
  def method  
   @v = 1  
  end  
 end  
 a = A.new  
 a.class # => A  

1) Instance Variables:

Objects contain instance variables, Ruby provides a method Object#instance_variables() to peek at them.

In the above example we have just one instance variable

 a.method  
 a.instance_variables # => [:@v]  

Unlike in static languages like Java, in Ruby there is no connection between an object's class and its instance variables.

Instance Variables come into existence whenever you assign them a value. Important thing to understand is that you can have objects of the "same" class that carry different sets of instance variables


Lets look at the following example:

 class A  
   def method  
     @v = 1  
   end  
   def new_method  
     @c = 2  
   end  
 end  
 a = A.new  
 a.method  
 a.instance_variables #=> [:@v]  
 b = A.new  
 b.new_method  
 b.instance_variables #=> [:@c]  


So if we hadn't called a.method() or b.new_method() objects a or b would not have any instance variables.


2) Methods

Besides having instance variables objects have methods

You can see an objects methods by calling Object#methods(). Most of the methods will be the methods inherited from Object so this list of methods will be quite long.

We can use Array#grep() to find the method we are looking for

 a.methods.grep(/new_/) #=> [:new_method]   


3) Classes: Yes, classes are nothing but objects in ruby and since a class is an object, everything that applies to an object also applies to a class.

Classes like any object have their own class, called Class

"hello".class # => String

The method of an object are the instance methods of its class. 
Methods of a class are the instance methods methods of Class.

No comments:

Post a Comment