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.rb204 chars12 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.rb23 chars2 lines
Now we can call the methods that are defined in ParentClass
and ChildClass
on this instance:
main.rb149 chars3 lines
So, with subclassing, we can reuse code that's defined in the superclass and add additional functionality in the subclass.
gistlibby LogSnag