From: Intransition Date: 2013-01-06T18:31:22+09:00 Subject: Re: respond_to_missing? ------=_Part_417_6839807.1357464179726 Content-Type: multipart/alternative; boundary="----=_Part_418_32711429.1357464179727" ------=_Part_418_32711429.1357464179727 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit On Saturday, January 5, 2013 4:00:02 PM UTC-5, Jan E. wrote: > > How is that contradictory? Are you sure you got the return values of > respond_to_missing? right? Because I guess you want to return *true* for > :to_ary? > > respond_to? first checks if the method is actually, physically there. If > that's not the case, it checks for respond_to_missing? > > In your case both checks return "false", so you end up with "false" just > like you should. > > Yes, that is what it should do. But notice #flatten doesn't seem to notice that it returns false. It still calls #to_ary on it, class Baz def method_missing(s); s; end def respond_to_missing?(s, x) return false if s == :to_ary true end end [Baz.new].flatten => in `flatten': can't convert Baz to Array (Baz#to_ary gives Symbol) (TypeError) Even though it appears to work fine if one overrides #respond_to? directly. class Baz def method_missing(s); s; end def respond_to?(s, x) super unless s == :to_ary end end [Baz.new].flatten => [#] ------=_Part_418_32711429.1357464179727 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: 7bit
On Saturday, January 5, 2013 4:00:02 PM UTC-5, Jan E. wrote:
How is that contradictory? Are you sure you got the return values of
respond_to_missing? right? Because I guess you want to return *true* for
:to_ary?

respond_to? first checks if the method is actually, physically there. If
that's not the case, it checks for respond_to_missing?

In your case both checks return "false", so you end up with "false" just
like you should.


Yes, that is what it should do. But notice #flatten doesn't seem to notice that it returns false. It still calls #to_ary on it,

    class Baz
      def method_missing(s); s; end

      def respond_to_missing?(s, x)
        return false if s == :to_ary
        true
      end
    end

    [Baz.new].flatten
    => in `flatten': can't convert Baz to Array (Baz#to_ary gives Symbol) (TypeError)

Even though it appears to work fine if one overrides #respond_to? directly.

    class Baz
      def method_missing(s); s; end

      def respond_to?(s, x)
        super unless s == :to_ary
      end
    end
 
    [Baz.new].flatten => [#<Baz:0x007f8d3115c7d0>]

------=_Part_418_32711429.1357464179727-- ------=_Part_417_6839807.1357464179726--