Ruby 3.1.xだと継承ツリーに後からincludeでモジュールを追加できる

Ruby技術者認定試験Goldの勉強をしていてRubyのバージョンによって変わっている挙動を知ったのでメモ。

検証コード

module M1
  def method_1
    __method__
  end
end

class C
  include M1
end

p C.new.method_1

module M2
  def method_2
    __method__
  end
end

module M1
  include M2
end

p C.new.method_2

Ruby 2.7.6

:method_1
Traceback (most recent call last):
a.rb:23:in `<main>': undefined method `method_2' for #<C:0x0000000148184c48> (NoMethodError)
Did you mean?  method
               method_1
               methods

Ruby 3.1.2

:method_1
:method_2