Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overwriting instance methods via multiple includes

Take the following code in ruby 3.3.0:

module A
  def print
    puts "A"
  end
end

module B
  def print
    puts "B"
  end
end

class C
end

c_instance = C.new

C.send(:include, A)
c_instance.print

C.send(:include, B)
c_instance.print

C.send(:include, A)
c_instance.print

I expected it to print out:

A
B
A

But it prints out

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A
B
B

Why is that?

>Solution :

Ruby ignores the second call.
From Ruby docs:

Ruby’s default implementation is to add the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors. See also Module#include

This is a quote from append_features method description, which is used in include method

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading