Hi --

On Sat, 24 Jun 2006, Roger Johansson wrote:

> Ok, thanks I think im sort of getting the picture now :-P
>
> "MyType" is an instance of class "Class".
> this instance has a metaclass , which holds the static methods for
> MyType.
>
> eg in pseudo c#ish code:
>
> RubyClass MyType = new RubyClass();
> MyType.Meta = new RubyMetaClass();
> MyType.Meta.StaticMethods.Add("some_method",args);
>
> would that be a correct view of the object/class relations in this case?
>
> this seems fair enough but what I dont get is why are static methods and
> instance methods stored in different places?
>
> in other languages(or rather implementations of languages) instance
> methods are just syntax sugar for a static method with a "this" pointer
> as the first arg. but they are still stored at the same palce.
>
> what I dont get is why I only need to do the "class << self" thing when
> aliasing static methods and not instance methods.
>
> Why are the instance methods accessable in the context of MyType ?
>
>
> ...hmmm.. maybe I get it now ..
>
>
> the meta class is a runtime class which has the actual static methods as
> real methods , not just a list of methods as in my pseudo sample?
>
> it would be more like:
>
> RubyClass MyType = new RubyClass();
> MyType.Meta = new ConcreteMetaClassForMyType(); //<--
>
> and every call to a static method is just directed to the meta class?
> and since MyType is not only an instance of Class , it is also a
> "class",
> so MyType is a class that has the instance methods.
> and the meta has the static methods of MyType as instance methods?
>
> or should I go to sleep now?
> this is weird :-P

I'm tired too (and a little spacy, having just spent 1.5 hours at a
Why the Lucky Stiff performance :-)  But I can give you this advice:
forget the term "static method".  It only clouds the picture.  Other
than that, you're very close.

Every object (almost, but don't worry about the exceptions right now)
can have its own methods, as well as the methods it gets from its
class.  The way Ruby organizes this special category of
object-specific methods is by creating an object-specific class.

It's that object-specific class that you gain access to when you do:

   class << some_object

You're inside some_object's singleton class -- that is, the class
where the singleton methods of some_object are defined.

some_object can be (but does not have to be) a Class object.  When you
see:

   class SomeClass
     class << self
       def whatever

you're seeing the singleton method "whatever" being added to the
object SomeClass, courtesy of opening up that object's singleton class
and defining a method there.


David

-- 
David A. Black (dblack / wobblini.net)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

See what the readers are saying about "Ruby for Rails"!
http://www.rubypowerandlight.com/quotes