Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Metaprogramming and instance variables

0 views
Skip to first unread message

Michael Lesniak

unread,
Jun 15, 2006, 4:34:36 AM6/15/06
to
Hello,

I'm reading whys poignant guide to ruby at the momemt and am in the
chapter of metaprogramming. There is one thing in the Creature-Example
I don't understand.

A short example to exemplify
--- snip ---
class Foo
def self.method(val)
@var = val
p instance_variables
end
end

class Bar < Foo
method true
end
--- snap ---

Execution returns "[@var]". But since @var is an instance-variable,
where is is stored. Shouldn't it be set first when an instance is
allocated?

Thanks for help,
Michael

Daniel Schierbeck

unread,
Jun 15, 2006, 5:06:03 AM6/15/06
to

See, that's the point -- it's an instance variable of the *class*.
Classes are objects like any other, and they can have instance
variables, too. Foo.method isn't defined in Foo itself, but rather in
Foo's metaclass (or singleton class or eigenclass, we can't really
decide.) You could also define it this way:

class Foo
# this gets us the metaclass
# remember, `self' is `Foo'
class << self
def method
...
end
end
end


Cheers,
Daniel

Marcin Mielżyński

unread,
Jun 15, 2006, 7:53:21 AM6/15/06
to
Michael Lesniak wrote:
>
> Execution returns "[@var]". But since @var is an instance-variable,
> where is is stored. Shouldn't it be set first when an instance is
> allocated?
>
> Thanks for help,
> Michael
>

http://www.whytheluckystiff.net/articles/seeingMetaclassesClearly.html

lopex

0 new messages