作为编程练习,我编写了一个Ruby代码段,创建一个类,实例化该类中的两个对象,monkeypatches一个对象,并依赖monkeypatch另一个缺少的方法_.
事情是这样的.这样做的目的是:
class Monkey
def chatter
puts "I am a chattering monkey!"
end
def method_missing(m)
puts "No #{m}, so I'll make one..."
def screech
puts "This is the new screech."
end
end
end
m1 = Monkey.new
m2 = Monkey.new
m1.chatter
m2.chatter
def m1.screech
puts "Aaaaaargh!"
end
m1.screech
m2.screech
m2.screech
m1.screech
m2.screech
您会注意到,我有一个参数表示方法_缺失.我这样做是因为我希望使用define_方法来动态创建具有适当名称的缺少的方法.然而,它不起作用.事实上,即使使用带有静态名称的define_方法,如下所示:
def method_missing(m)
puts "No #{m}, so I'll make one..."
define_method(:screech) do
puts "This is the new screech."
end
end
以以下结果结束:
ArgumentError: wrong number of arguments (2 for 1)
method method_missing in untitled document at line 9
method method_missing in untitled document at line 9
at top level in untitled document at line 26
Program exited.
让错误信息更令人困惑的是,我只有一个method_missing
的论点...