1

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)
Community
  • 1
  • 1
McKrassy
  • 961
  • 2
  • 10
  • 19

1 Answers1

3

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • But how do you explain the behaviour that the link shared in the question says? – LPD Dec 30 '12 at 04:11
  • I don't think that's true. Check out this post here: http://stackoverflow.com/questions/9014764/have-a-parent-classs-method-access-the-subclasss-constants, in which Animal can " puts self.class::NOISE" without ever declaring NOISe itself (see answer by Phrogz, second code block). Also, modules get access to the instance variables of the classes they are included in; so I don't think your statement is correct for modules either. – McKrassy Dec 30 '12 at 04:11
  • 2
    LPD, McKrassy You are confusing what the receiver is. Look carefully. In those cases, the constructor is applied to `Dog`, and not `Animal`. `Dog` has all the extra things; `Animal` does not. – sawa Dec 30 '12 at 04:16