How are respond_to and respond_to_missing different?

前端 未结 1 1729
梦谈多话
梦谈多话 2021-01-06 01:46

I\'m confused when to use each of this methods. From respond_to? documentation:

Returns true if obj responds to the given meth

相关标签:
1条回答
  • 2021-01-06 02:23

    respond_to_missing? is supposed to be updated when you make available additional methods using the method missing technique. This will cause the Ruby interpreter to better understand the existence of the new method.

    In fact, without using respond_to_missing?, you can't get the method using method.

    Marc-André posted a great article about the respond_to_missing?.

    In order for respond_to? to return true, one can specialize it, as follows:

    class StereoPlayer
      # def method_missing ...
      #   ...
      # end
    
      def respond_to?(method, *)
        method.to_s =~ /play_(\w+)/ || super
      end
    end
    p.respond_to? :play_some_Beethoven # => true
    

    This is better, but it still doesn’t make play_some_Beethoven behave exactly like a method. Indeed:

    p.method :play_some_Beethoven
    # => NameError: undefined method `play_some_Beethoven'
    #               for class `StereoPlayer'
    

    Ruby 1.9.2 introduces respond_to_missing? that provides for a clean solution to the problem. Instead of specializing respond_to? one specializes respond_to_missing?. Here’s a full example:

    class StereoPlayer
      # def method_missing ...
      #   ...
      # end
    
      def respond_to_missing?(method, *)
        method =~ /play_(\w+)/ || super
      end
    end
    
    p = StereoPlayer.new
    p.play_some_Beethoven # => "Here's some_Beethoven"
    p.respond_to? :play_some_Beethoven # => true
    m = p.method(:play_some_Beethoven) # => #<Method: StereoPlayer#play_some_Beethoven>
    # m acts like any other method:
    m.call # => "Here's some_Beethoven"
    m == p.method(:play_some_Beethoven) # => true
    m.name # => :play_some_Beethoven
    StereoPlayer.send :define_method, :ludwig, m
    p.ludwig # => "Here's some_Beethoven"
    

    See also Always Define respond_to_missing? When Overriding method_missing.

    0 讨论(0)
提交回复
热议问题