有没有办法计算Ruby方法被调用的次数? [英] Is there a way to count how many times a Ruby method is called?
本文介绍了有没有办法计算Ruby方法被调用的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby 有没有办法计算一个方法被调用了多少次?我知道 caller.first
为您提供了文件名、行号和调用方方法名称,但找不到任何进一步的相关信息.
Is there a way in Ruby to count how many times a method is called? I know that caller.first
gives you the file name, line number, and caller method name, but couldn't find any further related information.
推荐答案
使用 TracePoint
在调用方法时运行代码块,然后根据方法名称进行过滤.
Use TracePoint
to run a block of code whenever a method is called, then filter based on the method name.
def foo() end
count = 0
name = :foo
TracePoint.trace(:call) do |t|
count += 1 if t.method_id == name
end
count # => 0
foo
count # => 1
foo
count # => 2
count
这里只是一个由 .trace
块关闭的局部变量.您可以将其调整为常量、实例变量或任何最适合您的用例的变量.
count
here is simply a local variable that is closed over by the .trace
block. You can adjust this to be a constant, or an instance variable, or whatever best suits your use case.
这篇关于有没有办法计算Ruby方法被调用的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文