What does Module.private_constant do? Is there a way to list only private constants?

Starting with Ruby 1.9.3, we can create private constants:

module M class C; end private_constant :C end 

Is there any good documentation on what this does? Is there a way to get the names of only private constants similar to calling constants

+8
private ruby constants
source share
2 answers

Starting with Ruby 2.1, Module#constants only includes public constants, if you set inherit=false , you will also get private constants. Therefore, if you find a constant in constants(false) , but not in constants (and you do not need inherited constants), this can be a more or less reliable way of saying whether it is confidential.

 class Module def private_constants constants(false) - constants end end module Foo X = 1 Y = 2 private_constant :Y end puts "Foo.constants = #{Foo.constants}" puts "Foo.constants(false) = #{Foo.constants(false)}" puts "Foo.private_constants = #{Foo.private_constants}" # => Foo.constants = [:X] # => Foo.constants(false) = [:X, :Y] # => Foo.private_constants = [:Y] 

This is undocumented, and I'm not sure if he intends, but empirically it works. I would support this with unit tests.


Update: It looks like this is a bug in Ruby and may disappear in a future version.

+3
source share

There are no such things as private constants until Ruby 1.9.3. To get a list of all constants, you can simply use #constants .

 module Mod CONST = "value" end Mod.constants #=> [:CONST] 

From 1.9.3 added .private_constant , but since nothing is really private, you can do ...

 module Mod CONST = "value" private_constant :CONST end Mod.const_get(:CONST) #=> "value" 

I don’t think there is a way to get a list of all private constants, but you can still check for a specific name.

 Mod.const_defined?(:CONST) #=> true 
+9
source share

All Articles