McKrassy
McKrassy

Reputation: 991

Ruby: Getting access to a subclass constant

Why does the following not work?

class Foo
    def self.keyletters
        self::KEYLETTERS
    end
end

class Baz < Foo
    KEYLETTERS = "US"
end

puts Foo.keyletters

I have seen questions for similar problems (eg. here: Have a parent class's method access the subclass's constants), but in my case Foo.keyletters is a class-method, not an instance method. I am getting

uninitialized constant Foo::KEYLETTERS (NameError)

Upvotes: 1

Views: 709

Answers (1)

sawa
sawa

Reputation: 168101

When class A inherits class B or includes/extends module C, then A gets whatever B and C have, in addition to its own constants, variables and methods. B and C are not affected by that.

In your case, Baz is a subclass of Foo. So Baz has whatever Foo has, in addition to Baz::KEYLETTERS. Foo does not have anything in addition. Particularly, there is no Foo::KEYLETTERS.

Upvotes: 3

Related Questions