Search code examples
ruby

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

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