メタプログラミングRubyを読んで(3)
5.5まで(一部理解できてない)
特異メソッド
a = [1,2,3] b = [1,2,3] c = a def a.xx self.inject(:+) end a.xx # => 6 b.xx # NoMethodError: undefined method `xx' for [1, 2, 3]:Array c.xx # => 6 [1,2,3].xx # NoMethodError: undefined method `xx' for [1, 2, 3]:Array c = a c.xx # => 6 c.clone.xx # => 6 c.dup.xx # NoMethodError: undefined method `xx' for [1, 2, 3]:Array a.methods(false) # => [:xx] b.methods(false) # => []
cloneは特異メソッドもコピーするがdupはしない。 http://docs.ruby-lang.org/ja/2.2.0/class/Object.html#I_CLONE
a = [1,2,3] a.xx # NoMethodError: undefined method `xx' for [1, 2, 3]:Array class << a def xx self.inject(:+) end end a.xx # => 6 a.singleton_class # => #<Class:#<Array:0x00000003eb4cd8>> a.singleton_class.superclass # => Array
オブジェクトの特異メソッドは特異クラスにある。
class Aaa def self.aaa "aaa" end end Aaa::aaa # => "aaa"
クラスメソッドはクラスの特異クラスにある特異メソッド。
理解しきれてないけど疲れたので今日はここまで。
Pry version 0.10.4 on Ruby 2.3.0
メソッドをメゾットだと思ってた。