[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Basic question about Ruby's class hierarchy

Patrick Li

8/11/2008 3:22:00 AM

Hi,
I thought I understood this, but apparently not.

What is this object exactly?
o = class << String; self; end

From my understanding:
p o
and
p String
should output the same thing.

but it doesn't
p o #<Class:String>
p String #String

Thanks for answering such a basic question for me.
-Patrick
--
Posted via http://www.ruby-....

2 Answers

Eric I.

8/11/2008 4:09:00 AM

0

On Aug 10, 11:22 pm, Patrick Li <patrickli_2...@hotmail.com> wrote:
> I thought I understood this, but apparently not.
>
> What is this object exactly?
> o = class << String; self; end
>
> From my understanding:
> p o
> and
> p String
> should output the same thing.
>
> but it doesn't
> p o #<Class:String>
> p String #String

o is not the same as String. o is String's metaclass. The exact role
that metaclasses play is Ruby's take on object-oriented programming is
too much for an answer post such as this. But you might want to read
why's explanation at:

http://www.whytheluckystiff.net/articles/seeingMetaclassesCl...

Eric

====

Rails training and Ruby training available at http://Lea... .
On-site and customized training are available.

Chris Shea

8/11/2008 4:13:00 AM

0

On Aug 10, 9:22 pm, Patrick Li <patrickli_2...@hotmail.com> wrote:
> Hi,
> I thought I understood this, but apparently not.
>
> What is this object exactly?
> o = class << String; self; end
>
> From my understanding:
> p o
> and
> p String
> should output the same thing.
>
> but it doesn't
> p o #<Class:String>
> p String #String
>
> Thanks for answering such a basic question for me.
>   -Patrick
> --
> Posted viahttp://www.ruby-....

In your example, String is an instance of Class, and o is the
eigenclass (or metaclass) of String. Maybe this will help clarify:

o = class << String; self; end
o.class_eval do
def backwards
'gnirtS'
end
end

String.backwards # => "gnirtS"

HTH,
Chris