Kernel#caller

caller([start [, length]]) -> [string]
Returns: Array · Updated March 13, 2026 · Kernel Methods
debugging stack trace introspection

The caller method returns the execution stack as an array of strings. Each element represents a location in the call stack, showing file path, line number, and sometimes method name.

Basic Usage

def one
  caller
end

def two
  one
end

puts two.first
# => /path/to/file.rb:10:in `two'

Practical Examples

Debugging

def log_call
  puts "Called from:"
  caller(1).each { |loc| puts "  #{loc}" }
end

def a
  log_call
end

def b
  a
end

b

# Output:
# Called from:
#   /path/to/file.rb:15:in `b'

Error Messages

def validate!(value)
  unless value
    raise ArgumentError, "Value required", caller(1)
  end
end

Stack Depth

def depth
  caller.length
end

def level1
  depth
end

def level2
  level1
end

puts level2  # => 3

Filtering Stack

# Skip first few frames
def trace
  caller(3)  # Skip 3 frames
end

Raise Without Trace

# Useful for libraries to show user code in errors
def my_raise(msg)
  raise msg, caller(1)
end

Format

def show_caller
  caller(0).each_with_index do |c, i|
    puts "#{i}: #{c}"
  end
end

# Output format:
# 0: /path/file.rb:10:in `method_name'
# 1: /path/file.rb:20:in `another_method'

Practical Library Usage

Logging

def debug(message)
  location = caller(1).first
  puts "[DEBUG] #{Time.now} #{location}: #{message}"
end

Assertions

def assert(condition, message = "Assertion failed")
  return if condition
  raise "Assertion failed: #{message}", caller(1)
end

Deprecation Warnings

def deprecated_method(*args)
  warn "deprecated_method is deprecated", caller.first
  # ... old implementation
end

Method Tracer

def trace_method(method)
  original = instance_method(method)
  
  define_method(method) do |*args|
    puts "Calling #{method} with #{args.inspect}"
    result = original.bind(self).call(*args)
    puts "Returned: #{result.inspect}"
    result
  end
end

Performance Note

caller creates the full stack trace, which can be slow. Use sparingly in production code.

See Also