Write class inheritance in Ruby

I will write how to inherit and use the method defined in the parent class in another new class.

The way to write is as follows.

class Child class name

end

First, let's look at an example of a parent class.

class Mos def eat puts "eat" end

def drink puts "drink" end

def take_out puts "take-out" end end

Next, let's look at an example of an inherited child class.

class Mcdo <Mos # class inheritance def smile puts "smile free" end end

The methods of the parent class can be used by other inherited classes </ strong>.

Method name Mos(Parent class) Mcdo(Child class)
eat
drink
take_out
smile ×

Looking at the above figure, you can see the eat, drink, and take_out described in the method of the parent class. You can see that it can be inherited by the child class. However, smile, which is a method of child class Mcdo, is Mos of parent class. Is not inherited by.

In other words class Child class name <Parent class name end By writing as follows, while inheriting the method of the parent class in another class, a new method can be created. You can add.

Recommended Posts