Iterate only common Ruby constants

Since Ruby 2.0 or so, private use of private_constant could be made permanent, resulting in an error if the constant is used directly outside the declaring module.

However constants and const_defined? private constants still return, and const_get allows access to them. Is there a way to programmatically identify private constants and filter them at runtime?

(Note: What does Module.private_constant do? Is there a way to list only private constants? And its answer does not specifically address this case, but rather the opposite (how to list only private constants).)


Update: It appears that in Ruby 1.9 and 2.0 constants only included public constants. Starting from 2.1, no-arg constants still includes only public constants, but when setting inherit to false using constants(false) (i.e., enumerate only the constants defined in this module and not in its ancestral modules) has side effect of exposing private constants.

+7
ruby private members
source share
1 answer

You can identify the constants as follows:

 class A C = "value" private_constant :C C2 = "value2" end A.constants #public constants #=> [:C2] A.constants(false) #public & private constants #=> [:C, :C2] A.constants(false) - A.constants #private constants #=> [:C] 
+4
source share

All Articles