๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby TracePoint

TracePoint watches method calls while a chosen piece of code runs. It reports each call and return as it happens, then switches itself off.

Watching one call

The tracer watches the :call and :return events. Around one greet call, it prints the event and the method name for each.

def greet(name)
  "Hello, #{name}"
end

tp = TracePoint.new(:call, :return) do |point|
  puts "#{point.event} #{point.method_id}"
end

tp.enable do
  greet("Ana")
end

Counting calls of one method

The counter hash starts every name at zero. Each :call event adds one under the method name, and the total prints after the block.

def step(value)
  value + 1
end

counts = Hash.new(0)
tp = TracePoint.new(:call) do |point|
  counts[point.method_id] += 1
end

tp.enable do
  step(1)
  step(2)
  step(3)
end
puts counts[:step]

Tracing stops with the block

The wave call inside the enable block prints its name once. The wave call after the block prints nothing, because tracing is already off.

def wave
  "wave"
end

tp = TracePoint.new(:call) do |point|
  puts point.method_id
end

tp.enable do
  wave
end
wave
puts "done"

Example

def inner(value)
  value * 2
end

def outer(value)
  inner(value) + 1
end

tp = TracePoint.new(:call, :return) do |point|
  puts "#{point.event} #{point.method_id}"
end

tp.enable do
  puts outer(10)
end

Key points

  • TracePoint.new builds a tracer from the events it should watch.
  • The :call event fires when a method starts and :return fires when it ends.
  • enable runs its block with tracing on and turns tracing off at the end.
  • The handler block receives the trace point for each event.
  • Each event carries a method_id that names the method.

In this example, the tracer watches calls and returns around one outer call. outer calls inner, so the events nest in order. The answer 21 prints after the final return.

Note

A counter hash beside the tracer can count the calls of one method.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A TracePoint watches :call and :return around one call to a method named total. Which lines print, in order?