小编gau*_*uth的帖子

Ruby:define_method vs. def

作为一个编程练习,我编写了一个Ruby片段,它创建了一个类,从该类中实例化了两个对象,monkeypatches一个对象,并依赖于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
Run Code Online (Sandbox Code Playgroud)

你会注意到我有一个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
Run Code Online (Sandbox Code Playgroud)

结束以下结果:

ArgumentError: wrong number of arguments (2 for 1) …
Run Code Online (Sandbox Code Playgroud)

ruby metaprogramming

66
推荐指数
1
解决办法
4万
查看次数

标签 统计

metaprogramming ×1

ruby ×1