定义的意义何在respond_to_missing?
而不是定义respond_to?
?如果重新定义会出现什么问题respond_to?
某堂课?
Without respond_to_missing? http://ruby-doc.org/core/Object.html#method-i-respond_to_missing-3F已定义,尝试通过获取该方法method http://ruby-doc.org/core/Object.html#method-i-method将失败:
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>
马克-安德烈 https://stackoverflow.com/users/8279/marc-andre-lafortune(Ruby 核心提交者)有一个很好的博客文章于respond_to_missing? http://blog.marc-andre.ca/2010/11/methodmissing-politely.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)