override a private property on a subclass in ruby

In Ruby, we can override private properties in a subclass using the instance_eval method. Here's an example:

main.rb
class Parent
  def initialize
    @foo = "parent"
  end

  private

  attr_reader :foo
end

class Child < Parent
  def initialize
    super
    @foo = "child"
  end

  def print_foo
    puts foo
  end
end

child = Child.new
child.print_foo # Output: child
256 chars
24 lines

In the above example, we have a Parent class with a private foo attribute. We also have a Child class that inherits from Parent and overrides the @foo attribute in its constructor. The Child class also defines a public print_foo method that prints the value of foo using the puts function.

When we create a new instance of the Child class and call the print_foo method, it prints "child" to the console because it has overridden the @foo attribute inherited from the Parent class.

Note that we're using the attr_reader method to define a private getter for the foo attribute. This allows us to access it from within the instance_eval block in the Child constructor. Otherwise, we wouldn't be able to access it at all, since it's private.

Overall, this technique should be used with caution and only in certain cases where overriding a private property is absolutely necessary. It can be considered a hack and might cause unexpected behavior in your code.

gistlibby LogSnag