Apr 15, 2007 @ 05:30 pm

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 :

  1. class Monkey
  2.   def Monkey.laughs
  3.      "Ou ou ou Ahh ahh AHHH!" #that’s how a monkey laughs
  4.   end
  5. end
  6.  
  7. mvp = Monkey.new
  8. mvp.class.laughs
Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon
Rate this post :
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...
Posted under : short & sweet
4 Comments
MyAvatars 0.2

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

Comment by : Dan
— April 15, 2007 @ 6:13 pm

MyAvatars 0.2

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

Comment by : manveru
— April 18, 2007 @ 5:21 am

MyAvatars 0.2

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

Comment by : Frank
— April 18, 2007 @ 12:42 pm

MyAvatars 0.2

hi
6pmw62rr3txncph6
good luck

Comment by : Emanuel Williams
— January 9, 2009 @ 1:07 pm




Leave a comment
Name (required)
Email (will not be publish) (required)
Website