override a static property on a subclass in ruby

To override a static property (a class variable) on a subclass in Ruby, you can simply define the same class variable on the subclass, and it will override the one defined on the superclass. Here's an example:

main.rb
class Parent
  @@class_var = "Hello from Parent"

  def self.class_var
    @@class_var
  end
end

class Child < Parent
  @@class_var = "Hello from Child"
end

puts Parent.class_var # Output: "Hello from Parent"
puts Child.class_var # Output: "Hello from Child"
261 chars
15 lines

In the example above, we define a class variable @@class_var on the Parent class, and then define the same class variable on the Child class, with a different value. When we call the class_var method on each class, we get the corresponding value defined in each class.

Note that class variables have some limitations in Ruby, and can sometimes lead to unexpected behavior, especially when subclassing. As an alternative, you may want to consider using class instance variables instead, which work more consistently in subclassing scenarios.

gistlibby LogSnag