What is the difference between response_to and reply_to_missing?

I am confused when using each of these methods. From the documentation respond_to?:

Returns true if obj matches this method. Private methods are included in the search only if the optional second parameter is true.

If the method is not implemented, like Process.fork on Windows, File.lchmod on GNU / Linux, etc. It returns false.

If the method is not defined, answer_to_missing? the method is called and the result is returned.

And respond_to_missing?:

Hook method to return whether obj can respond to the id method or not.

See #respond_to ?.

Both methods take 2 arguments.
Both methods seem the same (check if any object responds to this method), so why should we use (have) both?

"resond_to_missing?" :

class A
  def method_missing name, *args, &block
    if name == :meth1
      puts 'YES!'
    else
      raise NoMethodError
    end
  end

  def respond_to_missing? name, flag = true
    if name == :meth1
      true
    else
      false
    end
  end
end

[65] pry(main)> A.new.method :meth1
# => #<Method: A#meth1>

respond_to? ?

:

respond_to? , :

  • .
  • .
  • .

respond_to_missing? , :

  • method_missing:

:

def method_missing name, *args, &block
  arr = [:a, :b, :c]
  if arr.include? name
    puts name
  else
    raise NoMethodError
  end
end

:

class A
  def initialize name
    @str = String name
  end

  def method_missing name, *args, &block
    @str.send name, *args, &block
  end
end

2. , .

/ ( ):

1.9.3 ( ), respond_to_missing?, respond_to?

:

? - ? , / , .

+4
1

respond_to_missing? , , . Ruby .

, respond_to_missing?, , method.

- respond_to_missing?.

_? true, :

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

, play_some_Beethoven , . :

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

Ruby 1.9.2 respond_to_missing?, . respond_to? respond_to_missing?. :

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 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 some_Beethoven"
m == p.method(:play_some_Beethoven) # => true
m.name # => :play_some_Beethoven
StereoPlayer.send :define_method, :ludwig, m
p.ludwig # => "Here some_Beethoven"

. response_to_missing? method_missing.

+4

All Articles