[Ruby] Writing class inheritance in Ruby

1 minute read

I will write the method of inheriting and using the method defined in the parent class in other new classes.

The way to write is as follows.

class Child class name <Parent class name


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 “takeaway” end end

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

class Mcdo <Mos # class inheritance def smile puts “smile free” end end

The methods of the parent class can also be used in other inherited classes.

Method name Mos (parent class) Mcdo (child class)
smile ×

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

That is class child class name <parent class name end By writing like this, the new method is inherited while inheriting the method of the parent class in another class. You can add it.