override a setter on a subclass in ruby

To override a setter on a subclass in Ruby, you can define a new method with the same name as the setter in the parent class. Then, you can use the super keyword to call the parent class setter and add any additional logic as needed. Here's an example:

main.rb
class Parent
  def x=(value)
    @x = value
  end
end

class Child < Parent
  def x=(value)
    # call parent class setter
    super(value)

    # additional logic
    puts "New value of x is #{value}"
  end
end
212 chars
16 lines

In this example, we have a parent class Parent with a setter method x=. The child class Child overrides the x= method and calls the parent class setter with super(value). Then, it adds some additional logic to print out the new value of x.

You can create instances of the child class and set the value of x as follows:

main.rb
child = Child.new
child.x = 10
31 chars
3 lines

This will output:

main.rb
New value of x is 10
21 chars
2 lines

Note that the super keyword is used to call the parent class setter with the value argument. If you omit the argument to super, the parent class setter will be called with no arguments.

gistlibby LogSnag