Rick DeNatale said:
Consider:
class BigGuy
def initialize
@favorites = ["a","b","c"]
end
class << self
def display_favs
class_eval "p @favorites"
end
end
end
class LittleGuy < BigGuy
display_favs
end
Why does this display "nil"? I expected the initialize of BigGuy to
occur prior to invoking display_favs. Any other construction I should
be using to get my desire behavior of the constructor of the base class
getting called prior to singleton methods called from the child class?
"Initialize" is called when the class is instantiated (i.e. with new).
You are never instantiating this class, so "initialize" is never called.
True, but kind of beside the point.
Perhaps it's a matter of pedagogy. What *is* "the point"? That depends
on where one thinks the OP has ultimately gone wrong. The OP might have
any of several misconceptions (it is hard to be certain); the OP might
not be aware:
(1) that initialize is called at instantiation time.
(2) that a class and an instance of that class are different things.
(3) that the singleton method is a class method.
(4) that the @favorites referred to in the class method is not the
@favorites referred to in "initialize".
Each of us is trying to teach, so each of us, like a good teacher, made
a guess about where the heart of the OP's misunderstanding might lie. I
guessed (1), with a little bit of (2) thrown in. You are leaning more
toward (3) and (4). Your guess is reasonable, but my guess is not
unreasonable, especially since the OP explicitly said: "I expected the
initialize ... to occur". I spoke to that issue, showing why that
expectation was wrong. So what I said is hardly "beside the point".
m.
The initialize method if and when
it is called will set the instance variable @favorites in a new
INSTANCE of BigGuy.
class BigGuy
...
class << self
def display_favs
class_eval "p @favorites"
end
end
end
This makes display_favs a class method of BigGuy.
In the method display_favs self is the class object BigGuy.
so
class_eval "p @favorites"
is the same as
BigGuy.class_eval "p @favorites"
which is printing a class instance variable of BigGuy which doesn't exist.
And...
class LittleGuy < BigGuy
display_favs
end
inside this class definition, self is LittleGuy so
display_favs
is equivalent to:
LittleGuy.display_favs
which executes
BigGuy::display_favs
by inheritance
which prints the uninitialized class instance variable @favorites.
Note also that the class instance variable @favorite in BigGuy is
different from the clas instance variable @favorite in LittleGuy,
although neither one is initialized.
--
matt neuburg, phd = (e-mail address removed),
http://www.tidbits.com/matt/
Tiger -
http://www.takecontrolbooks.com/tiger-customizing.html
AppleScript -
http://www.amazon.com/gp/product/0596102119
Read TidBITS! It's free and smart.
http://www.tidbits.com