Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

TracePoint#enable

trace.enable(target: nil, target_line: nil, target_thread: nil) → true or false
trace.enable(target: nil, target_line: nil, target_thread: :default) { block } → obj

Activates the trace.

Returns true if trace was enabled. Returns false if trace was disabled.

Example
trace.enabled?  #=> false
trace.enable    #=> false (previous state)
                #   trace is enabled
trace.enabled?  #=> true
trace.enable    #=> true (previous state)
                #   trace is still enabled

If a block is given, the trace will only be enabled during the block call. If target and target_line are both nil, then target_thread will default to the current thread if a block is given.

Example
trace.enabled?
#=> false

trace.enable do
  trace.enabled?
  # only enabled for this block and thread
end

trace.enabled?
#=> false

target, target_line and target_thread parameters are used to limit tracing only to specified code objects. target should be a code object for which RubyVM::InstructionSequence.of will return an instruction sequence.

Example
t = TracePoint.new(:line) { |tp| p tp }

def m1
  p 1
end

def m2
  p 2
end

t.enable(target: method(:m1))

m1
# prints #<TracePoint:line test.rb:4 in `m1'>
m2
# prints nothing

Note: You cannot access event hooks within the enable block.

Example
trace.enable { p tp.lineno }
#=> RuntimeError: access from outside

Ruby version changes

  1. 3.2
    • TracePoint#enable target_thread keyword argument now defaults to the current thread if a block is given and target and target_line keyword arguments are not passed. [Bug #16889]

See also #disable #enabled? #defined_class #eval_script also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0