LoginSignup
0
0

More than 5 years have passed since last update.

トップレベルとextendに関する不思議な挙動

Posted at

テストした環境

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

テストコード

def toplevel_hello
  puts "toplevel_hello"
end

class Test1
  def initialize
    toplevel_hello
  end
end

module ModHello
  def mod_hello s
    puts "mod_hello #{s}"
  end
end

class Test2
  def initialize
    extend ModHello
    mod_hello self
  end
end

class Test3
  def initialize
    mod_hello self
  end
end


Test1.new
Test2.new

extend ModHello
mod_hello self
Test3.new rescue puts 'Fail extended method'

include ModHello
Test3.new rescue puts 'Fail included method'

結果

toplevel_hello
mod_hello #<Test2:0x007effdd6aaae8>
mod_hello main
Fail extended method
mod_hello #<Test3:0x007effdd6aa638>

結果より分かること

Test1より
トップレベルに定義したメソッドはクラス内からも(何の苦労もなく)呼べます
Test2より
モジュールで定義したメソッドもself.exetend使うことで呼べるようになります
問題のTest3
トップレベルでextend使うとトップレベルオブジェクト(main)にメソッドが追加されるのですが
main.extend の場合はクラス内で使用できず
main.include の場合はクラス内で使用できるようになりました

exetendで特異メソッド生やすのがなんとなく好きだったのですが
(そのせいでincludeの存在を忘れてた)
トップレベルの場合はincludeを使わないと変なハマり方をするようです

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