Search code examples
rubyaccess-specifierclass-constants

How to I make private class constants in Ruby


In Ruby how does one create a private class constant? (i.e one that is visible inside the class but not outside)

class Person
  SECRET='xxx' # How to make class private??

  def show_secret
    puts "Secret: #{SECRET}"
  end
end

Person.new.show_secret
puts Person::SECRET # I'd like this to fail

Solution

  • You can also change your constant into a class method:

    def self.secret
      'xxx'
    end
    
    private_class_method :secret
    

    This makes it accessible within all instances of the class, but not outside.