LoginSignup
1
0

More than 5 years have passed since last update.

おもしろメタプログラミング/2章

Last updated at Posted at 2017-09-09

二章 月曜日オブジェクトモデル

目次

  • 2.1 オープンクラス => ハンズオン モンキーパッチ
  • 2.2 オブジェクトモデルの中身
    • 2.2.1 オブジェクトの中身
    • 2.2.2 クラスの真相 => クイズ クラス
    • 2.2.3 定数
    • 2.2.4 オブジェクトとクラスのまとめ
    • 2.2.5 ネームスペースを使う
  • 2.3 クイズ: 引かれてない線
  • 2.4 メソッドを呼び出すときに何がおこなわれているの?
    • 2.4.1 メソッド探索 => 説明 ハンズオン メソッド探索
    • 2.4.2 メソッド実行
    • 2.4.3 Refinements
  • 2.5 クイズ:絡み合ったモジュール
  • 2.6 まとめ

ハンズオン モンキーパッチ

1, String classに新しいメソッドを追加しよう
2, String classの既存のメソッドを上書きしよう

ex)

$ vim monkey_patch.rb

monkey_patch.rb
class String
  def monkey_patch_method
    p 'I am monkey patch'
  end

  def to_i
    p 'to_i is overridden'
  end
end

'a string'.monkey_patch_method
'1'.to_i

$ ruby monkey_patch.rb

クイズ クラス

1, 'mystring'.class #=> ?

2, String.class #=> ?

3, Class.class #=> ?

class MyClass < String
end

4, MyClass.superclass #=>?

5, String.superclass #=> ?

6, Object.superclass #=> ?

7, BasicObject.superclass #=> ?

8, Class.superclass #=> ?

クイズ self

class SomeClass
  self
  def initialize
  end

  def self.class_method
    p self
  end

  def some_method
    p self
  end
end

説明 メソッド探索

my_object = MyClass.new
my_bject.my_method

メソッド探索のルールは
「Classに入って(右へ一歩)、SuperClassを登る(それから上へ)」

※ClassにModuleがインクルードされてたら、Classの上に入れる

ハンズオン メソッド探索

module M1
end

module M2
  include ::M1
end

module M3
  prepend ::M1
  include ::M2
end


p M3.ancestors

1, M3.ancestors #=>?

module PrependedModule
  def some_method
    p 'prepended module'
  end
end

module SomeModule
  prepend PrependedModule
  def some_method
    p 'some module'
  end
end

class SuperClass
  def some_method
    p 'super class'
  end
end

class SubClass < SuperClass
  include SomeModule
end

SubClass.new.some_method

2, SubClass.new.some_method #=> ?

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