add a getter to a subclass in ruby

To add a getter method to a subclass in Ruby, you can define the method with the appropriate name and scope within the subclass. For example:

main.rb
class Parent
  attr_accessor :parent_property
end

class Child < Parent
  def child_property
    @child_property
  end
end
123 chars
10 lines

In this example, we define a Parent class with a property that has a getter and a setter. We then define a Child class that inherits from Parent and define a getter method for a new property child_property which is not defined on the Parent class.

Note that if you want to access the parent class's property with the same name as the child class's property, you can use the super keyword like this:

main.rb
class Parent
  attr_accessor :property
end

class Child < Parent
  def property
    super + " (from child)"
  end
end
118 chars
10 lines

In this example, we define a Parent class with a property that has a getter and a setter. We then define a Child class that inherits from Parent and define a getter method for the same property property. We use the super keyword to call the parent method, and then append the string " (from child)" to the end of the parent's value.

related categories

gistlibby LogSnag