How to access a class method from an instance

If you bet that this post would fall in the “short & sweet” category, you won… a new car! (The price is right music starts while Bob Barker looks at you with a subtile smile)

To access a class method from an instance, you have to use a reference to that class (because that’s where the method resides). The attribute reader returning that reference is named class :

  • http://www.javascriptkata.com Dan

    I like it. Most languages don’t make the difference between a call to a class method and a call to an instance method.

  • manveru

    I certainly don’t mind if you do this in your code, but i suggest you use

    def self.laughs

    and also think about how many you have to change when you suddenly decide that Monkey should be called Primate… using self in these cases can save you some typing ;)

    see following post which is loosly related:
    http://www.oreillynet.com/ruby/blog/2007/04/nubygems_be_kind_to_your_child.html

  • http://www.rubyfleebie.com Frank

    You are bringing up a good point. It’s true that if you change your class name, you could have some tedious search and replace operations to do depending on the size of your class. But personally it’s a price I’m willing to pay. To me it’s more a matter of clarity than anything else. The fact that you can have the word “self” pointing to different things inside the same class (sometimes to an instance, sometimes to the class itself) just doesn’t please me that much. However, I have to agree that this practice is more convenient in some situations.

    Thanks for your comment

  • http://stndf.com/qhcaddb.html Emanuel Williams

    hi
    6pmw62rr3txncph6
    good luck