`respond_to?` vs. `respond_to_missing?` `respond_to?` vs. `respond_to_missing?` ruby ruby

`respond_to?` vs. `respond_to_missing?`


Without respond_to_missing? defined, trying to get the method via method will fail:

class Foo  def method_missing name, *args    p args  end  def respond_to? name, include_private = false    true  endendf = Foo.newf.bar  #=> []f.respond_to? :bar  #=> truef.method :bar  # NameError: undefined method `bar' for class `Foo'class Foo  def respond_to? *args; super; end  # “Reverting” previous redefinition  def respond_to_missing? *args    true  endendf.method :bar  #=> #<Method: Foo#bar>

Marc-André (a Ruby core committer) has a good blog post on respond_to_missing?.


It's a good practice to create respond_to_missing? if you are overriding method_missing. That way, the class will tell you the method you are calling exists, even though it's not explicitly declared.

respond_to? should probably not be overriden :)