override a getter on a subclass in ruby

In Ruby, you can override a getter method in a subclass by simply defining a new method with the same name as the getter in the superclass. Here's an example:

main.rb
class Animal
  attr_reader :name
  
  def initialize(name)
    @name = name
  end
  
  def speak
    raise NotImplementedError, "Subclass must implement this method"
  end
end

class Cat < Animal
  def name
    "My name is #{super}"
  end
  
  def speak
    puts "Meow"
  end
end

my_cat = Cat.new("Fluffy")
puts my_cat.name # Output: "My name is Fluffy"
my_cat.speak # Output: "Meow"
385 chars
26 lines

In the example above, we have a superclass Animal with a getter method name. We then define a subclass Cat and override the name method to add some additional text to the output. We also define a speak method in the Cat subclass.

When we create a new Cat instance and call name on it, we get the overridden behavior that we defined in the Cat subclass. Similarly, when we call speak on the Cat instance, we get the speak method that we defined in the Cat subclass, which overrides the speak method in the Animal superclass.

Note that if you don't define a getter method in the subclass, the getter method from the superclass will still work as expected. In the example above, if we had not overridden the name method in the Cat subclass, calling my_cat.name would have returned just "Fluffy".

gistlibby LogSnag