override a property on a subclass in ruby

To override a property on a subclass in Ruby, you can define a new property of the same name in the subclass, and then override the getter and/or setter methods to provide the desired behavior. Within the overridden getter or setter method, you can call super to access the implementation of that method in the superclass.

Here's an example:

main.rb
class Animal
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def speak
    puts "Hello, I'm an animal."
  end
end

class Cat < Animal
  def speak
    super
    puts "#{@name} says meow."
  end
end

cat = Cat.new('Felix')
cat.speak
# Output:
# Hello, I'm an animal.
# Felix says meow.
308 chars
25 lines

In this example, we override the speak method in the Cat subclass to call super to access the implementation of speak in the Animal superclass, and then add additional behavior to print the cat's name and the word "meow".

gistlibby LogSnag