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.rb205 chars13 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