作为一个编程练习,我编写了一个 Ruby 片段,它创建一个类,从该类实例化两个对象,对一个对象进行猴子补丁,并依靠 method_missing 对另一个对象进行猴子补丁。
这是交易。这按预期工作:
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
您会注意到我有一个method_missing 参数。我这样做是因为我希望使用 define_method 来动态创建具有适当名称的缺失方法。但是,它不起作用。事实上,即使使用带有静态名称的 define_method,如下所示:
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
...