1
1

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 3 years have passed since last update.

Rubyのクラスがモジュールをinlcudeする時の参照順を実験してみた

Last updated at Posted at 2020-04-05

確認したいこと

同名のモジュールが複数の名前空間に存在する時のincludeの参照順

実験


module TalkActions
  def say_my_name ###(1)
    puts "I am #{@name}[outside]"
  end
end
  
class Human
  module TalkActions
    def say_my_name ###(2)
      puts "I am #{@name}[inside]"
    end
  end

  include TalkActions ###(1),(2)のどちらをよみこむか?
  def initialize(name)
    @name = name 
  end
end
  
John = Human.new("John")
John.say_my_name ### I am John[inside] (2)だった
  • 一応insideをコメントアウトして実行

module TalkActions
  def say_my_name ###(1)
    puts "I am #{@name}[outside]"
  end
end
  
class Human
  # module TalkActions
  #   def say_my_name ###(2)
  #     puts "I am #{@name}[inside]"
  #   end
  # end

  include TalkActions ###ちゃんと(1)を読み込んでいることの確認
  def initialize(name)
    @name = name
  end
end
  
John = Human.new("John") 
John.say_my_name ### I am John[outside] (1)が呼び出された

なお、TalkActionsモジュールは今回ルートだったので呼び出せすことができた。

  • TalkActionsモジュールをルートにしないと、
module X
  module TalkActions
    def say_my_name ###(1)
      puts "I am #{@name}[outside]"
    end
  end
end

class Human
  # module TalkActions
  #   def say_my_name ###(2)
  #     puts "I am #{@name}[inside]"
  #   end
  # end

  include TalkActions ###ちゃんと(1)を読み込んでいることの確認
  def initialize(name)
    @name = name
  end
end

John = Human.new("John") 
John.say_my_name ### '<class:Human>': uninitialized constant Human::TalkActions (NameError) を吐いて終了。

結論

呼び出し元のと同一名前空間内→ルートのモジュールへと探しにいくようだ。

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?