add a static property to a class in ruby

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.rb
class MyClass
  @@static_property = "Hello, world!"

  def self.static_property
    @@static_property
  end
end
112 chars
8 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.rb
class MyClass
  @@static_property = "Hello, world!"

  def self.static_property
    @@static_property
  end

  def self.set_static_property(value)
    @@static_property = value
  end
end

puts MyClass.static_property #=> "Hello, world!"
MyClass.set_static_property("Goodbye, world!")
puts MyClass.static_property #=> "Goodbye, world!"
335 chars
16 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