add a private static property to a class in ruby

To add a private static property to a class in Ruby, you can use the class << self syntax to define a private class-level instance variable. Here's an example:

main.rb
class MyClass
  class << self
    private
    @my_private_property = "secret value"

    public
    def my_method
      # access the private property here
      puts @my_private_property
    end
  end
end
205 chars
13 lines

In this example, we've defined a private class-level instance variable @my_private_property inside a class << self block. We've marked it as private using the private keyword, and then made it accessible to methods defined inside the same block with public.

To access this private property from a method within the same class, we can simply refer to @my_private_property, as shown in the my_method example. Any attempt to access the property from outside the class or from a subclass will result in a NoMethodError or NameError.

gistlibby LogSnag