`respond_to?` vs. `respond_to_missing?`

陌路散爱 提交于 2019-12-20 08:56:08

问题


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 class?


回答1:


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  #=> #<Method: Foo#bar>

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




回答2:


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 :)



来源:https://stackoverflow.com/questions/13793060/respond-to-vs-respond-to-missing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!