如何在课堂和混合模块中使用method_missing
?
module Bar
def method_missing(name, *args)
p 'Bar' if name =~ /bar/
end
end
class Foo
include Bar
def method_missing(name, *args)
p 'Foo' if name =~ /foo/
end
end
a = Foo.new
a.foofoo => "Foo"
a.barbar => nil
答案 0 :(得分:5)
使用super
:
module Bar
def method_missing(name, *args)
p 'Bar' if name =~ /bar/
end
end
class Foo
include Bar
def method_missing(name, *args)
p 'Foo' if name =~ /foo/
super # ⇐ HERE
end
end
a = Foo.new
a.foofoo => "Foo"
a.barbar => "Bar"
正如@ndn在评论中指出的那样,人们可能会仔细处理不同的结果。当且仅当super
实施未成功时,Foo#method_missing
可能会被调整使用:
def method_missing(name, *args)
case name
when /foo/ then p 'Foo'
# .....
else super # ⇐ HERE
end
end