super doesn't just call the methods of the parent class

Introduction

I'm studying for ruby gold acquisition. My understanding of super changed and I wanted to share it.

Main subject

First of all, what kind of result will be output when the following code is executed?


module M
  def foo
    super
    puts "M#foo"
  end
end

class C2
  def foo
    puts "C2#foo"
  end
end

class C < C2
  def foo
    super
    puts "C#foo"
  end
  include M
end

C.new.foo

Option 1

C2#foo C#foo

Option 2

C2#foo M#foo C#foo

Option 3

Error is displayed

I always thought it was 1. By the way, the correct answer is option 2 If you understand it properly and answer it correctly, you don't have to look anymore. Thank you for watching so far.

First, how did I choose option 1

"C class foo method, hmm hmm" "Oh, super? You just have to look at the parent class foo." "I see, the answer is 1!"

It is like this. I thought it wouldn't be called when I included the module.

Let's learn about the super class. First of all, briefly about super described in Reference Manual

super calls the method that the current method is overriding

I see, it doesn't seem to call a superclass method. Now let's use the ancestors method.

##abridgement

class C < C2
  def foo
    super
    puts "C#foo"
  end
  include M
  self.ancestors #=> [C, M, C2, Object, Kernel, BasicObject]
end

C.new.foo

ancestors is a method that shows the search order of methods in a simple way. For example, when the foo method is executed, it looks for the C foo method, and if not, it searches for M foo ....

Now let's look at the code in question again.

module M
  def foo
    super #Reference foo in C2
    puts "M#foo"
  end
end

class C2
  def foo
    puts "C2#foo"
  end
end

class C < C2
  def foo
    super #Refer to M's foo
    puts "C#foo"
  end
  include M
  self.ancestors #=> [C, M, C2, Object, Kernel, BasicObject]
end

C.new.foo
#=> C2#foo
#=> M#foo
#=> C#foo

Conclusion

--If there is a description of super, the next method will be searched. --Does not search for methods of the parent class

in conclusion

If you are studying for qualifications, you will deepen your understanding, so if you have little practical experience, you may try studying.

Recommended Posts

super doesn't just call the methods of the parent class
Various methods of the String class
Call a method of the parent class by explicitly specifying the name in Ruby
How to mock some methods of the class under test
Call the super method in Java
[Ruby] Summary of class definitions. Master the basics.
About next () and nextLine () of the Scanner class
First touch of the Files class (or Java 8)