Search code examples
rubytrace

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


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.


Solution

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