Understanding class methods in ruby

First of all, let’s go back to the basics. What we generally call a class method is a method that resides at the class level. On the opposite, an instance method is a method that resides at the object level.

#UPDATE 2007/04/15
I changed the previous paragraph and removed the word ‘shared’ when talking about class methods because it was confusing. A class method isn’t ‘shared’ since it’s instances cannot access it without using explicitly the reference to the class, like that : my_obj.class.class_method. And no, unlike someone have suggested, the super keyword won’t work. I’ve just been too quick to update my post… sorry)
END UPDATE

In ruby, classes are also objects, so the methods you define as class methods only exist in the object that defined them (the class) and nowhere else. If you define my_class_method in a class named Test, my_class_method will only live into the object Test, which is an instance of a built-in ruby class named Class. If what I just said sounded like mandarin, you might want to read this post first.

Every instances that you create contain a variable that points to their corresponding class. Say you create a new instance of class Test and that you name this instance x (x = Test.new). x will contain every instance variables/methods that have been defined as such in the class as well as a reference to the object Test, which will contain the variables that need to be shared among every instances of this class (class variables) as well as methods that will be local to this object (class methods). That’s the reason why ruby complain when you write something like x.my_class_method. It complains because my_class_method just doesn’t reside in x, it resides in Test.

You have 2 ways for defining a class method.

1) You can use the name of the class directly

2) You can use the self variable, which is always pointing to the current object

Once you understand that classes are objects, this use of the self variable to define a class method finally makes sense.

In fact, there is another way to define a class method. I personally find it a little bit more obscure. it consists of building a new anonymous class only for the current object (self). To create the anonymous class, we use the << notation.

Remember what we have to do to add a new instance method in a class :

When you look at it, it's exactly the same trick that we previously used to add a new class method. The only difference is that instead of adding a method to an instance of class Class, we added a method to an instance of class Test.

The value of self

Not too surprinsingly, when you are inside a class method, the value of self refers to the object that holds the class structure (the instance of class Class). This means that :

is equivalent to :

When you are inside an instance method, the value of self still refers to the current object. This time however, the current object is an instance of class Test, not an instance of class Class.

  • http://www.mr-eel.com Mr eel

    ‘A class method isn’t ’shared’ since it’s instances cannot access it.’

    This isn’t actually true. An instance can access a class method via super. Like so:

    self.super.class_method

  • http://www.rubyfleebie.com Frank

    Hmmm… I should have check your code before actually update my post (I’m learning how to blog everyday). You cannot access a class method the way you have indicated. super is for super classes, not for class methods.

  • http://clintonforbes.blogspot.com Clinton Forbes

    Great post, as usual, Fleebie.

    I was aware that I could define class methods using:

    def self.class_method

    But I didn’t know about:

    def Test.class_method

    I will start using the second method because it is a lot clearer to me.

  • http://www.rubyfleebie.com Frank

    Thanks Clinton,

    I also prefer to use Test.class_method over self.class_method. It just feels more natural and intuitive to me.

  • Paolo Perrotta

    Most Ruby coders actually prefer self.class_method to Test.class_method. The main rationale is that Test.class_method violates the “Don’t Repeat Yourself” principle – you’re repeating the name of the class in different places. If the name changes, you’ll have to change it into all class methods definition.

    As with all matters of style, YMMV.

  • sadeesh

    these basic are really useful to me to understand the class methods especially example with the notation “

  • rubywannabe

    I see a lot of class

  • rubywannabe

    FYI my post got cut off

  • rubywannabe

    Ah, I think I know what happened. Your blog cuts off comments with &lt in it, if they’re entered as the less than character instead of “amper l t” . what I originally said was, “I see a lot of class &lt&lt, which I also find off-puttingly unclear. I think a lot of people do it becuase it’s obsure and therefore “cool”. Great post.”

  • twitfreak

    good to know! Thanks a million!

  • eyeplum

    Great post! Helps me a lot in understanding self/super/self.view, etc…

  • Rama

    Great Post!

  • http://boddhisattvadedicates.blogspot.in boddhisattva

    Thanks :) Very useful.

  • R_G

    Kind of cool that a post lives on and is very informative. But, I do have a concern.

    You said: x will contain every instance variables/methods that have been defined as such in the class as well as a reference to the object Test, which will contain the variables that need to be shared among every instances of this class (class variables) as well as methods that will be local to this object (class methods).

    That last phrase is confusing. Is it accurate? It seems to be a reference to the “sharing” of class methods. To my mind, an instance has neither class variables nor class methods?

  • R_G

    Alright, my confusing reigns. I misread the statement and didn’t see my error until I posted the comment. I missed the change from variable x to class Test… Thanks for the info.

  • Zach

    thanks. cleared up confusion

  • Pingback: Class vs Instance: Variables, Methods and more | Coding in the Craft Room()

  • Pingback: To use self. or not.. in Rails | ASK AND ANSWER()

  • Pingback: Backend-programmer going frontend |()