At first I will try to make clearer what is the context in which
the class method Emplyee::print_class
is defined:
# top-level context
class Employee
end
module Person
module Employee
class Officer
# context_a the context of case 1
## here the constant Employee is a Module
p (Employee.class) # -> Module
# ## If you want a reference to a constant defined at the top-level(the Employee class)
# # you may preceded it with ::
p ::Employee.class # -> class
p ::Employee == Employee # -> false
end
end
end
class Person::Employee::Officer
#context_b the context of case 2
# here The constant Employee is the class Employee
# There are not Employee Constant defined in this context
# the constant look up will reach the top-level context
# and Employee will reference to ::Employee
p (Employee.class) # -> Class
p ::Employee == Employee # -> true
end
Now we can take into consideration the method Emplyee::print_class
definition and execution.
When you defined the method Emplyee::print_class
you used the constant Employee
:
When and in which context this constant is evaluated to be a class or a module or a string?
def self.print_class(obj)
obj.is_a? Employee
end
The answer to when is: when the method is executed.
The answer to in which context is: the context where you defined the method, not the one you execute it. For the Constant is the outer scope of the method definition (If you try to create a constant inside the method you will get an error 'dynamic constant assignment').
In your example case 1 the context will be context_a.
In your example case 2 the context will be context_b, but the constant look-up will reach the top-level context.
puts
is nil. Is that the problem? – Paralipomena