I have a bone to pick with the generally-wonderful Pickaxe regarding
“Top-Level Execution Environment”, which states:
At the top-level, we’re executing in the context of some predefined
object [of class Object]. When we define methods, we’re actually
creating (private) instance methods for class Object.
The second sentence is true and helpful. But the first sentence is only
sort of true, and only because of some unexplained magic. Here’s what I
I’m not aware that “in the context of some … object” has an
established meaning other than what “instance_eval” does; and
“instance_eval” does not provide a context for constant definitions.
Also, “instance_eval” interprets "def"s in the context of the
singleton-class of the object (I think), which is inconsistent with the
second (correct) sentence.
The second sentence remedies both of these deficiencies. But the
consistency of the two sentences requires some magic: Most code of
interest is evaluated in the context of “class Object … end”, AND self
is not Object.
Mightn’t it be better to have self == Object at the top-level? Then no
magic would be required.
PS: My interest in eliminating the magic is that I built up some very
bad intuition from seeing methods invoked in their definition context.
It would have helped a lot if I had initially seen:
def foo ; "foo" ; end # a method of all objects foo # same as self.foo; and self (ie, Object) is an object
This is tricky. But because it is not magical, it teaches something