Metaclasses in Ruby

Well, I don't have any drawings of cartoon characters for you, but I do feel like making a post about Ruby.

I've been learning the Ruby programming language as I use it in some projects. So far, it's been a breath of fresh air after the rigidity of C++. Although C++ is very powerful, it can be kind of clumsy. I've been using a mixed approach in some projects, where Ruby code invokes C code.

Recently, I found myself playing in the deep end of the language. Every programming language has a deep end, whether or not it's advertised as a feature. With Ruby, the really hard part seems to be understanding the singletons.

Every object has a singleton which holds methods specific to that object. So the singleton can be viewed as sitting in between an object and its class. This is how you can add methods to an individual object.

In other words:
class C; def foo; puts "hi"; end; end
c = C.new
class <<c; def bar; puts "bar"; end; end
c.bar ==> "bar"

Even though the class of c was C, the singleton of c held a method called bar, which we could invoke. As Why the Lucky Stiff says, "the hidden singleton lurks behind everything."

Now the singleton is an object in its own right, and can even have its own singleton. Most people don't find this useful. One thing that people do find useful is pulling out the singleton from an object with a construct like
def get_singleton; class <<self; self; end; end

Of course, the real fun comes when you start playing with singletons of Classes. Since Classes are Objects in Ruby, they also have singletons. I can't say that I understand all the implications yet. But you sure can do some cool things.

Note: some people call singletons "metaclasses," but the language designer views that as a misnomer.


At 5:38 AM, Anonymous Anonymous said...

jp成人,熊貓貼圖,成人圖片,成人文章,正妹,成人小說,杜蕾斯成人,ut 聊天室,熊貓貼圖區,交友聊天找e爵,ol制服美女影片,777成人區,bt成人,女同志聊天室,貼圖片區,一葉情貼圖片區,6k聊天室,69成人,成人貼圖站,色情影片,聊天室ut,免費成人影片,成人漫畫,0204貼圖區,小高聊天室,歐美免費影片,情色視訊聊天室,4u成人,pc交友,尋夢園聊天聯盟,玩美女人影音秀,666成人,免費視訊,聊天,情色論壇,視訊,成人文學,成人電影,漫畫貼圖,情色自拍,

At 9:36 AM, Anonymous Anonymous said...

快樂是你與生俱來的權力,它不應該取決於你完成什麼。 ..................................................

At 11:12 AM, Anonymous Anonymous said...


At 6:07 PM, Anonymous Anonymous said...



Post a Comment

<< Home