5. instance FirstClass
class FirstClass
def hanako
end
end
instance = FirstClass.new
instance.hanako
インスタンスは
自分のクラスにメソッドを
探索しにいく
6. class FirstClass
def hanako
end
end
クラスは
インスタンス間で共通
instance FirstClass
instance2
instance = FirstClass.new
instance.hanako
!
instance2 = FirstClass.new
instance2.hanako
7. class FirstClass
def hanako
“tarou”
end
end
instance FirstClass
instance2
モンキーパッチで
クラスのメソッド書き換える
instance.hanako
instance2.hanako
8. 自分のクラスにメソッドが
見つからなければ
継承元を探索
Sub
継承
class Super
def hanako
“super”
end
end
!
class Sub < Super
end Sub.new.hanako
#<Sub>
Super
9. MixInも継承ツリーに
差し込まれる
MyClass
module Mix
def hanako
“mix”
end
end
!
class Mixed
include Mix
end
Mix-In
Mixed.new.hanako
#<Mixed>
Mix
10. module Mix1
def hanako
“1”
end
end
!
module Mix2
def hanako
“2”
end
end
!
class Mixed2
include Mix1
include Mix2
end
どうなるかためしてみよう!
継承ツリーをみてみよう!
Mix-In × 2
Mixed2.new.hanako
11. includeはincludeされる
クラスのすぐ上に差し込む
Mix2の方が後によばれるので
Mix2のメソッドが呼ばれる
Mixed2
module Mix1
def hanako
“1”
end
end
!
module Mix2
def hanako
“2”
end
end
!
class Mixed2
include Mix1
include Mix2
end
Mix-In × 2
Mixed2.new.hanako
#<Mixed2>
Mix1
Mix2
13. BasicObject
Kernel
Blank
class Blank
end
スーパークラスを指定
されなかったクラスは暗黙的に
Objectクラスを継承する
Blank.new.to_s Object
#<Blank>
14. モンキーパッチで
to_sメソッドの探索を
途中で止めてみよう!
BasicObject
Kernel
モンキーパッチsuper
Blank
class Blank
end
class Object
def to_s
“obj: [#{super}]”
end
end
Blank.new.to_s Object
#<Blank>
15. BasicObject
Kernel
MyClass
class Super
def hanako
end
end
!
module Mix
def hanako
end
end
!
class Sub < Super
include Mix
end
継承+MixIn
MyClass.new.hanako
Object
#<MyClass>
Super
Mix
16. Ruby 2.0 ~
BasicObject
Kernel
Mix
Prepend
module Mix
def hanako
log.info ( “call #{__method__}” )
super
end
end
!
class MyClass
prepend Mix
end
MyClass.new.hanako
Object
#<MyClass>
MyClass
22. Class Classに足してみる
class Class
def hanako
"Class#hanako"
end
end
!
class MyClass; end
MyClass.hanako # =>
String.hanako # =>
ためしてみよう!
23. Class Classに足してみる
class Class
def hanako
"Class#hanako"
end
end
!
class MyClass; end
無関係のクラスにまで
(°д°lll)
MyClass.hanako # => "Class#hanako"
String.hanako
27. クラスも特異クラスがある
BasicObject
Kernel
class MyClass; end
!
def MyClass.hanako
“hanako”
end
MyClass.hanako Object
Class
MyClass#<Class>
Module
#MyClass
28. class ~ endまでのselfはクラス自身なので
self.メソッドに書き換えれる
BasicObject
Kernel
class MyClass
def self.hanako
end
end
MyClass.hanako Object
Class
MyClass#<Class>
Module
#MyClass
32. 特異クラスをたどり終わると
クラスの探索に戻る
new をSuperでとめてみようModule
#BasicObject Class
#Object
Object
class Super
def self.new
end
end
!
class Sub
end
Sub#<Class>
BasicObject
#Sub
Super
#Super