add a public static property to a class in ruby

In Ruby, static properties do not exist as they do in some other languages. However, you can achieve the same result using class variables:

main.rb
class MyClass
  @@my_property = "Hello, world!"
  
  def self.my_property
    @@my_property
  end
  
  def self.my_property=(value)
    @@my_property = value
  end
end
168 chars
12 lines

This code defines a class MyClass and a class variable @@my_property that can be accessed by calling MyClass.my_property. The self. before the method name makes it a class method, and the = after the method name allows us to assign a new value to the property using the = operator.

Here's an example of how you would use it:

main.rb
puts MyClass.my_property # Outputs "Hello, world!"
MyClass.my_property = "Goodbye, world!"
puts MyClass.my_property # Outputs "Goodbye, world!"
144 chars
4 lines

gistlibby LogSnag