Ruby 有什么方法可以在 method_missing 之前捕获消息吗?
我知道 method_missing
是 Ruby 处理消息时的最后手段。我的理解是,它会沿着对象层次结构向上查找与符号匹配的声明方法,然后向下查找最低声明的 method_missing
。这比标准方法调用慢得多。
是否可以拦截在此之前发送的消息?我尝试重写 send
,这在显式调用 send
时有效,但在隐式调用时则无效。
I understand that method_missing
is something of a last resort when Ruby is processing messages. My understanding is that it goes up the Object hierarchy looking for a declared method matching the symbol, then back down looking for the lowest declared method_missing
. This is much slower than a standard method call.
Is it possible to intercept sent messages before this point? I tried overriding send
, and this works when the call to send
is explicit, but not when it is implicit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知没有。
性能最佳的方法通常是使用
method_missing
动态地将方法添加到类的调用中,这样开销就只会产生一次。从那时起,它像任何其他方法一样调用该方法。例如:
运行时会输出以下内容:
Not that I know of.
The most performant bet is usually to use
method_missing
to dynamically add the method being to a called to the class so that the overhead is only ever incurred once. From then on it calls the method like any other method.Such as:
Which spits out this when run: