Jaka jest różnica kiedy robięrubin self.class.class_eval lub singleton_class.class_eval
class T
def initialize
self.class.class_eval do
def test
return self.class.object_id
end
end
end
end
i
class T
def initialize
singleton_class.class_eval do
def test
return self.class.object_id
end
end
end
end
Thanks
PS. Tass odpowiedział, że w tym przykładzie singleton_class zwróci inny id_obiektu dla każdego nowego obiektu, ponieważ singleton_class należy do tylko jednego obiektu. Ale IRB pokazy obok
1.9.2p180 :001 > class T
1.9.2p180 :002?>
1.9.2p180 :003 > def initialize
1.9.2p180 :004?> singleton_class.class_eval do
1.9.2p180 :005 > def test
1.9.2p180 :006?> return self.class.object_id
1.9.2p180 :007?> end
1.9.2p180 :008?> end
1.9.2p180 :009?> end
1.9.2p180 :010?>
1.9.2p180 :011 > end
=> nil
1.9.2p180 :012 > t = T.new
=> #<T:0x00000100ae9cb8>
1.9.2p180 :013 > t1 = T.new
=> #<T:0x00000100ad7ef0>
1.9.2p180 :014 > t1.test == t.test
=> true
1.9.2p180 :015 > t1.test
=> 2153233300
1.9.2p180 :016 > t.test
=> 2153233300
1.9.2p180 :017 >
Nie mogę znaleźć żadnej różnicy funkcjonalnej, ale myślę, że powinna być jedna. –
@JakubHampl, wygląda na to, że znalazłem różnicę) –
@AlexKliuchnikau Wiedziałem, że ktoś by to zrobił. +1 do ciebie! –