Kernel#trace_var

trace_var(symbol) {|new_value| block } -> symbol
Returns: Symbol · Updated March 13, 2026 · Kernel Methods
debugging variables tracing monitoring

The trace_var method monitors changes to global variables. When the variable is modified, the provided block is called with the new value. This is useful for debugging and monitoring.

Basic Usage

# Trace a global variable
$counter = 0

trace_var(:$counter) do |value|
  puts "Counter changed to: #{value}"
end

$counter = 5    # Prints: Counter changed to: 5
$counter = 10  # Prints: Counter changed to: 10

Practical Examples

Debugging Global State

$debug_mode = false

trace_var(:$debug_mode) do |value|
  puts "Debug mode #{value ? 'enabled' : 'disabled'}"
  $DEBUG = value
end

Configuration Changes

$config = { log_level: "info" }

trace_var(:$config) do |new_config|
  puts "Configuration changed: #{new_config}"
  apply_config(new_config)
end

$config = { log_level: "debug" }

Variable Access Logging

$cache = {}

trace_var(:$cache) do |value|
  timestamp = Time.now
  puts "[#{timestamp}] Cache updated: #{value.keys.size} entries"
end

Breaking on Changes

$important_value = 100

trace_var(:$important_value) do |val|
  if val < 0
    puts "WARNING: Value went negative!"
    # Could raise exception or log
  end
end

Untrace

# Remove the trace
trace_var(:$counter)  # Returns nil when no block given, or removes trace

Limitations

# Only works with global variables ($ prefix)
# local_var = 1
# trace_var(:local_var)  # Won't work!

# Works with these built-in globals
trace_var(:$LOAD_PATH) do |path|
  puts "Load path changed to: #{path}"
end

Comparison with attr_accessor

# For instance variables, use a different approach
class Config
  def self.value
    @value
  end
  
  def self.value=(val)
    puts "Setting to #{val}"
    @value = val
  end
end

Use Cases

  • Debugging global state changes
  • Implementing reactive global variables
  • Logging configuration changes
  • Memory profiling (tracking allocations)

See Also