In ruby, in a method defined in class << self, why can’t a constant defined on the superclass be access without self?

I'm trying to understand ruby singletons and class inheritance better. I read everywhere that

def self.method_name; end`

is equivalent to

class << self
  def method_name; end
end

But if that were true, then I would expect print_constant_fails to work, but it doesn't. What is going on here?

class SuperExample
  A_CONSTANT = "super example constant"
end

class SubExample < SuperExample
  def self.print_constant_works_1
    puts A_CONSTANT
  end
  class << self
    def print_constant_works_2
      puts self::A_CONSTANT
    end
    def print_constant_fails
      puts A_CONSTANT
    end
  end
end
pry(main)> SubExample.print_constant_works_1
super example constant

pry(main)> SubExample.print_constant_works_2
super example constant

pry(main)> SubExample.print_constant_fails
NameError: uninitialized constant #<Class:SubExample>::A_CONSTANT
from (pry):13:in `print_constant_fails'


Read more here: https://stackoverflow.com/questions/68491385/in-ruby-in-a-method-defined-in-class-self-why-cant-a-constant-defined-on-t

Content Attribution

This content was originally published by pduey at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: