Erich Lin
Erich Lin

Reputation: 105

Why does Array.constants not show the list of constants in Object class?

If I create:

class Test1
  A = 4
end

class Test2 < Test1
end

Test2.constants returns [:A] since it derives A from Test1. Array.constants is [] even though its superclass is Object and Object.constants has many values. How come Array does not derive those values?

Upvotes: 3

Views: 91

Answers (1)

Max
Max

Reputation: 22315

All top level constants in Ruby are added to Object as you have seen with Object.constants. The advantage of this is that every class inherits from Object, so all top level constants are always available (as you might intuitively expect).

Now suppose that Module#constants worked as you expected: every class lists the top level constants it inherits from Object. What a pain that would be! We would constantly be writing Foo.constants - Object.constants meaning "the constants other than the uninteresting ones that are always around".

The Ruby designers thought of this headache and added a special exception to rb_mod_const_of - the C function used to walk up the inheritance chain and find constants:

if (tmp == rb_cObject && mod != rb_cObject) break;

I.e. if we've reached Object in the inheritance chain, and we aren't looking for the constants of Object itself, stop looking.

Upvotes: 1

Related Questions