Going through Metaprogramming Ruby, and the author, Paolo Perrotta
points
out something I never paid attention to before.
class MyClass
def method_one
def method_two
“hello!”
end
end
end
obj = MyClass.new
obj.method_one
obj.method_two # => “Hello!”
my addition to show it is on MyClass, not obj’s singleton class
MyClass.new.method_two # => “hello!”
He uses this example to show that Ruby keeps track of the current class.
The
definition of method_two needs to know that it is being defined on, so
even
though it is being executed in an instance of MyClass, it is defined as
an
instance method of MyClass itself. This, understanding that Ruby keeps
track
of not only self, but also the current class, is then used to explain
the
difference between class_eval and instance_eval.
My questions are:
- Is any other situation where this information is relevant?
- Is there a way to access the current class? In the example below, you
can
see that both instance_eval and class_eval set self to the class, but I
can’t ask for the current class (the place methods would be defined on),
I
only know how to ask for self’s class.
class MyClass
end
MyClass.instance_eval do
self # => MyClass
self.class # => Class
def current_class_is_singleton; end
end
MyClass.class_eval do
self # => MyClass
self.class # => Class
def current_class_is_self; end
end
MyClass.instance_methods(false) # => [:current_class_is_self]
MyClass.singleton_methods # => [:current_class_is_singleton]