15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby で super を呼んだ時の呼ばれる順番

Posted at

気になったので調べた。

この順番で呼ばれる

  • 特異メソッド
  • extended module のメソッド
  • class構文に書かれたメソッド
  • included module のメソッド
  • 親クラスのメソッド

include、extend の位置は関係なくこの順番。

include, extend される module で同名のメソッドがあった場合は、最後に include, extend された順番になる。

親クラスですでに include されている module は、子クラスで再度 include されても順番は親クラスの位置。

("A".."H").each do |name|
  eval <<-MODULE
    module #{name}
      def hoge
        "#{name} -> " + super
      end
    end
  MODULE
end

class Base
  def hoge
    "Base"
  end
end

class TestClass < Base
  include A
  include B
  def hoge
    "TestClass -> " + super
  end
  include C
  include D
end

t = TestClass.new
t.extend E
t.extend F
def t.hoge
  "t -> " + super
end
t.extend G
t.extend H

p t.hoge #=> "t -> H -> G -> F -> E -> TestClass -> D -> C -> B -> A -> Base"

class TestClass2 < TestClass
  include A
  include B
  def hoge
    "TestClass2 -> " + super
  end
  include C
  include D
end

t = TestClass2.new
p t.hoge #=> "TestClass2 -> TestClass -> D -> C -> B -> A -> Base"
15
13
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?