gpt4 book ai didi

Ruby 有什么方法可以在 method_missing 之前捕获消息?

转载 作者:数据小太阳 更新时间:2023-10-29 08:33:47 26 4
gpt4 key购买 nike

我知道 method_missing 是 Ruby 处理消息时的最后手段。我的理解是,它在对象层次结构中向上寻找与符号匹配的已声明方法,然后向下寻找最低的已声明method_missing。这比标准方法调用慢得多。

是否可以拦截在此之前发送的消息?我尝试覆盖 send,这在显式调用 send 时有效,但在隐式调用时无效。

最佳答案

据我所知不是。

最高效的方法通常是使用method_missing 将被调用的方法动态添加到类中,这样开销只会产生一次。从那时起,它会像调用任何其他方法一样调用该方法。

如:

class Foo
def method_missing(name, str)

# log something out when we call method_missing so we know it only happens once
puts "Defining method named: #{name}"

# Define the new instance method
self.class.class_eval <<-CODE
def #{name}(arg1)
puts 'you passed in: ' + arg1.to_s
end
CODE

# Run the instance method we just created to return the value on this first run
send name, str
end
end

# See if it works
f = Foo.new
f.echo_string 'wtf'
f.echo_string 'hello'
f.echo_string 'yay!'

运行时会吐出这个:

Defining method named: echo_string
you passed in: wtf
you passed in: hello
you passed in: yay!

关于Ruby 有什么方法可以在 method_missing 之前捕获消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8888698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com