简体   繁体   English

我如何在Ruby中捕获方法的调用

[英]How can i trap invocation of methods in ruby

I want to trap invocation of a method and then display output. 我想捕获方法的调用,然后显示输出。

class A 

end

If i run new A.see it should trap and print 'unkown method'. 如果我运行新的A.see,它应该捕获并打印“未知方法”。

I am new to the language 我是该语言的新手

When you send a message to an object, the object executes the first method it finds on its method lookup path with the same name as the message. 当您向对象发送消息时,该对象将执行在其方法查找路径上找到的第一个方法,该方法与消息的名称相同。 If it fails to find any such method, it raises a NoMethodError exception, unless you have provided the object with a method called method_missing . 如果找不到任何此类方法,则除非您为对象提供了一个名为method_missing的方法,否则它将引发NoMethodError异常。 The method_missing method is passed the symbol of the non-existent method, an array of the arguments that were passed in the original call and any block passed to the original method. method_missing方法传递给不存在的方法的符号,在原始调用中传递的参数数组以及传递给原始方法的任何块。

class A 
  def method_missing(m, *args, &block)  
    puts "There's no method called #{m} here -- please try again."  
    super
  end  
end

这已经触发了NoMethodError,默认情况下会暂停程序。

NoMethodError: undefined method `see' for A:Class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM