add a setter to a subclass in ruby

To add a setter to a subclass in Ruby, you can define a method that takes a parameter and sets an instance variable, then call this method with the parameter in your subclass. Here's an example:

main.rb
class ParentClass
  def parent_method
    puts "This is a method from the parent class"
  end
end

class ChildClass < ParentClass
  def set_child_property=(value)
    @child_property = value
  end
end

my_child = ChildClass.new
my_child.set_child_property = "new value"
puts my_child.inspect
292 chars
16 lines

In this example, ChildClass inherits from ParentClass. We define a new method in ChildClass called set_child_property= that sets an instance variable @child_property to the value passed in. We create a new instance of ChildClass, call set_child_property= with a value, and then output information about the instance with puts my_child.inspect.

Note that set_child_property= is just an example method name; you can name your setter anything you like, as long as it follows the naming convention of ending with an equals sign.

gistlibby LogSnag