Metaprogramming and instance variables

M

Michael Lesniak

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
 
D

Daniel Schierbeck

Michael said:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top