2008-07-08

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.

4 Comments:

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

小老婆小老鼠成人網小老鼠成人小老鼠咆哮小老鼠網路小老鼠小磨女自拍小磨女小百無名小瓢蟲情論壇小瓢蟲情色論壇尋夢緣小魔女寫真少女色情自白小說小模女免費a片go免費a片cartoons免費a片bt免費a片a漫免費a片(近親亂倫)免費a片免費av線上觀看免費av線上看短片免費av線上看免費av線上直播免費av影區免費av小電影免費a片影片區AV女優裸体影片免費片線上看西洋的性愛寫真西洋白虎美女圖庫西洋男女性愛圖片西洋av貼圖西方裸體藝術影片西方絲襪辣妹襪做愛饑渴的女人褲襪正妹褲襪情人褲襪情色館熟女線上觀看視訊+聊天視訊美女live視訊美女(限)

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

肯定與支持你!!!加油囉~.........................

 

Post a Comment

<< Home