首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby: define_method与def

Ruby: define_method与def
EN

Stack Overflow用户
提问于 2008-10-09 04:31:47
回答 2查看 38.1K关注 0票数 66

作为编程练习,我编写了一个Ruby代码片段,它创建一个类,实例化该类中的两个对象,对一个对象进行monkeypatch,并依赖method_missing对另一个对象进行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

您会注意到我为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只有一个参数……

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/185947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档