`respond_to?` vs. `respond_to_missing?`

前端 未结 2 369
轻奢々
轻奢々 2021-01-31 07:37

What is the point of defining respond_to_missing? as opposed to defining respond_to?? What goes wrong if you redefine respond_to? for some

2条回答
  •  后悔当初
    2021-01-31 08:36

    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
      end
    end
    
    f = Foo.new
    f.bar  #=> []
    f.respond_to? :bar  #=> true
    f.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
      end
    end
    
    f.method :bar  #=> #
    

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

提交回复
热议问题