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 :

class Monkey
  def Monkey.laughs
     "Ou ou ou Ahh ahh AHHH!" #that's how a monkey laughs
  end
end
mvp = Monkey.new
mvp.class.laughs

4 thoughts on “How to access a class method from an instance

  1. 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

Leave a Reply to Dan Cancel reply

Your email address will not be published. Required fields are marked *