Prev - DUP - Next - TOC

Classes


The real world is filled by objects, and we can classify them. For example, when my one year old daughter sees a Saint Bernard or a German shepherd, she recognizes exactly `bowwow'. How smart a pattern recognition! Though, she may say `bowwow' when she find even a fox...

Joking aside, in terms of OOP, sort like bowwow is said `class', and on object belonging to a class is called `instance'.

To make an object in ruby and other many OOPLs, usually, first one defines the class to determine behavior of the object, then make it's instance that is the goal object. So let's define a class in ruby.

 ruby> class Dog
 ruby|   def bark
 ruby|     print "Bow Wow\n"
 ruby|   end
 ruby| end
 nil

In ruby, class definition is a region between the keywords `class' and `end'. A `def' in class syntax defines a method of the class.

Now we've gotten the class Dog so let's make an object.

 ruby> pochi = Dog.new
 #<Dog:0xbcb90>

It made a new instance of the class Doc and substituted it into the variable pochi. The method `new' of any class makes a new instance. Because the variable pochi has properties defined in the class Dog he can `bark'.

 ruby> pochi.bark
 Bow Wow
 nil

Prev - DUP - Next - TOC