To add a static property to a class in Ruby, we can use a class variable.
A class variable is a variable that is shared by all instances of a class. It is prefixed with @@
and is declared directly within the class definition.
Here's an example:
main.rb112 chars8 lines
In the code above, we declared a static property @@static_property
inside the class MyClass
. We can access the static property using the self.static_property
method which returns the value of @@static_property
.
We can also set the value of the static property using the @@
prefix:
main.rb335 chars16 lines
In the example above, we added a set_static_property
method which allows us to modify the value of @@static_property
. Note that when we change the value of the static property, it is reflected in all instances of the class.
gistlibby LogSnag