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.rb212 chars16 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.rb31 chars3 lines
This will output:
main.rb21 chars2 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