From: Rick DeNatale Date: 2007-12-14T07:58:41+09:00 Subject: Re: Newbie Question: What is a class for? On 12/13/07, Matthias Borgeson wrote: > Hello all- > > I am a newbie to Ruby and have just recently gotten the hang of using > methods to hop in and out of the main body of my programs and am moving > to my next concept. > > I am now trying to grasp what a class isand what is is for. I understand > that there a bunch of different classes, but how does that help me? > > While I think of methods as little tools I can create to do things > whenever I want in the main program, I have no idea how a class used? I > have the Pickaxe and Chris Pine's book, but whle describing classes, > neither text really helps me understand what a class is and how it > functions in a ruby program. > > I looked through my C++ book to understand methods and how they are > anologous to functions, but now I am just confused on the concept. > > Any help or a point in the right direction would be appreciated > > Thanks in advance Classes do several things. 1) They hold the methods for one or more objects. These methods are shared between those objects. For example consider this: class A def m "hello" end end The method m is available for any objects whose class is A to respond when sent the message m. 2) Most classes can be used to create objects of that class. For example: a = A.new This creates an object whose class is A and makes the variable a reference this new object. We can then send it the m message a.m and it will return "hello". This object is called an instance of A by virtue of A being its class. 3) classes can form a hierarchy, let's make a new class: class B < A end This syntax means that B is a subclass of A, or equivalently that A is B's superclass. methods available to instances of a class are also available to instances of any of its subclasses, so b = B.new.m will invoke the same method, as will just: B.new.m Subclasses can also override inherited methods: class B < A def m "Howdy" end end and now b.m will return "Howdy" instead of hello. We can also make use of the inherited method in the overriding method class B def m "#{super} there big fella!" end end and now b.m will return "hello there big fella!" 4) Classes act as name spaces - but this is a bit advanced for this reply. Every ruby object has a class, and classes themselves are objects, so classes themselves can have methods, but again, I've probably already given you enough to chew on. And I'd strongly recommend that you hide that C++ book while you are learning Ruby. It will confuse you more than it will help in the long run since the two languages take some radically different approaches and have radically different definitions of object orientation. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/