Re: Why do we need #respond_to_missing?

Victor Shepelev <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CANz6qH=MfYfpB1OU6d6s=v5+9-h_quB8JkQ6FWhjrczHFi=2HQ@mail.gmail.com>
If you imagine Ruby to be entirely implemented in Ruby, we can
(simplistically) say, that those methods are defined as following:

public

def respond_to?(name)
  methods.include?(name) || respond_to_missing?(name)
end

private

def respond_to_missing?(name)
  false
end

Then, in your code, if you implement method_missing, you typically redefine
respond_to_missing? (fallback method) only, which is simpler.

If you overriding just respond_to_missing?, you can be as simple as:

def respond_to_missing?(name)
  name.match?(MY_SPECIAL_METHOD_PATTERN)
end

If you'd override respond_to? instead, you'll need to not forget to call
super, and be ready for performance implications. If you'll be to naive,
like

# You forgot to return true for method defined the "normal" way
def respond_to?(name)
  name.match?(MY_SPECIAL_METHOD_PATTERN)
end

...then some other code may break unexpectedly, which just tried to check
whether you object had #to_s (to write it in logs, for example).

Hope this helps.

V.


сб, 19 янв. 2019 г. в 13:41, Greg Navis <[email protected]>:

> Hi!
>
> I was wondering why do we need #respond_to_missing? as a separate method.
> I tried searching for a rationale in the Ruby bug tracker but couldn't find
> it.
>
> I don't understand how it's different from overriding #respond_to? to
> match dynamic methods and calling super on other matches.
>
> The answer I'm NOT looking for is that #method wouldn't work, etc. as this
> is an answer to a different question ("Why do I need to override
> #respond_to_missing?").
>
> Why was Ruby designed in a way that introduces a distinction between
> #respond_to? and #respond_to_missing? It feels like I'm overlooking
> something simple.
>
> Best regards
> Greg Navis
>
> Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
>


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.