From: dblack@... Date: 2006-11-08T11:45:37+09:00 Subject: Re: Can't bind a singleton method to a subclass? Hi -- On Wed, 8 Nov 2006, David Walker wrote: > The behavior of this snippet doesn't make sense to me: > > class A > def A.class_method > puts "Class method worked in #{self}" > end > end > > class B < A; end > > aklass = (class << A; self; end) > bklass = (class << B; self; end) > > p RUBY_VERSION > > A.class_method > B.class_method > > p A.method(:class_method) > p B.method(:class_method) > p aklass.instance_method(:class_method) > p bklass.instance_method(:class_method) > p A.method(:class_method).unbind > p B.method(:class_method).unbind > p A.method(:class_method).unbind.bind(A) > p B.method(:class_method).unbind.bind(B) > > The output (for me) is: > > "1.8.4" > Class method worked in A > Class method worked in B > # > # > ##class_method> > ##class_method> > ##class_method> > ##class_method> > # > /workplace2/test.rb:24:in `bind': singleton method called for a > different object (TypeError) > from /workplace2/test.rb:24 > > In my mind, the last call should succeed, instead of raising an error. > Is it just plain impossible to re-bind the method to yield a # B(A).class_method>? The fact that B can call A.class_method is due to the special-casing of singleton classes of Class objects; it's the one case where a given object can execute singleton methods of another object. But those singleton methods still belong, unambiguously, to the first object, A. The reason B can call them is that A's singleton class serves as the superclass of B's singleton class -- so class_method lies on the method look-up path of B. But class_method is still defined only in A's singleton class. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org