[Understanding in 3 minutes] What is Ruby inheritance? Only the main points are explained in an easy-to-understand manner!

Introduction

When you start learning Ruby, you need to understand "inheritance". Even if you don't think hard, what is that? It will be summarized in 3 minutes so that it becomes.

Conclusion: Just stick together the duplicates

In the following, there are times when you think that [attr_accessor: a] and [def aa] are covered and inefficient. At that time, create a class C that summarizes the [attr_accessor: a] and [def aa] that are covered.

class A

  attr_accessor :a :b :c
  
    def aa
    end

    def aaa
    end
end

class B

  attr_accessor :c :d :e
  
    def aa
    end

    def bbb
    end
end


Create class C and let A and B inherit it

class C
#Two that I wrote many times are listed in the new class C
  attr_accessor :c
  
  def aa
  end
end

class A < C #<Same function as the first by writing C

  attr_accessor :b :c

    def aaa
    end
end

class B < C #<Same function as the first by writing C

  attr_accessor :d :e

    def bbb
    end
end


Keep in mind that the newly created class C is called the parent class, and the inherited classes A and B are called subclasses.

Recommended Posts

[Understanding in 3 minutes] What is Ruby inheritance? Only the main points are explained in an easy-to-understand manner!
What is the main method in Java?
[Ruby] What is an instance?
What are the rules in JUnit?
[Beginner] What is Docker in the first place? Easy-to-understand explanation from the basics!
[Technical memo] What is "include" in Ruby?