create a subclass in ruby

To create a subclass in Ruby, we use the class keyword followed by the name of the subclass and the name of the superclass that it is inheriting from. Here's an example:

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

class ChildClass < ParentClass
  def child_method
    puts "This is a method in the child class"
  end
end
204 chars
12 lines

In this example, ChildClass is inheriting from ParentClass using the < symbol, which indicates that ChildClass is a subclass of ParentClass. The ChildClass can now use any methods or attributes that are defined in ParentClass, as well as define its own methods.

To create an instance of the ChildClass, we can simply call the new method:

main.rb
child = ChildClass.new
23 chars
2 lines

Now we can call the methods that are defined in ParentClass and ChildClass on this instance:

main.rb
child.parent_method       # Output: "This is a method in the parent class"
child.child_method        # Output: "This is a method in the child class"
149 chars
3 lines

So, with subclassing, we can reuse code that's defined in the superclass and add additional functionality in the subclass.

gistlibby LogSnag