[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Metaprogramming and instance variables

michael.lesniak@gmail.com

6/15/2006 8:35:00 AM

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

2 Answers

Daniel Schierbeck

6/15/2006 9:06:00 AM

0

Michael Lesniak wrote:
> 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

Marcin Mielzynski

6/15/2006 11:53:00 AM

0

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

lopex