create a subclass with a constructor in ruby

To create a subclass in Ruby with a constructor, you would use the super method to call the parent class's constructor and pass any necessary arguments. Here's an example:

main.rb
class ParentClass
  def initialize(name)
    @name = name
  end
end

class SubClass < ParentClass
  def initialize(name, age)
    super(name)
    @age = age
  end
end
167 chars
13 lines

In this example, SubClass is a subclass of ParentClass, and it has its own constructor that takes two arguments: name and age. In the initialize method of SubClass, we call super(name) to invoke the constructor of ParentClass with the name argument, then we set the @age instance variable to the age argument. We can create a new instance of SubClass like this:

main.rb
sub_instance = SubClass.new("John", 25)
puts sub_instance.inspect #=> #<SubClass:0x00007f8cb28c8178 @name="John", @age=25>
123 chars
3 lines

This creates a new SubClass instance with a name of "John" and an age of 25. Calling inspect on the instance shows that it has both instance variables set correctly.

gistlibby LogSnag