Is there a way to count how many times a Ruby method is called?

不问归期 提交于 2019-12-12 03:15:21

问题


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.


回答1:


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 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.



来源:https://stackoverflow.com/questions/34732733/is-there-a-way-to-count-how-many-times-a-ruby-method-is-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!