How to get a stack trace object in Ruby?

pupeno picture pupeno · Sep 30, 2010 · Viewed 32.9k times · Source

I need to get a stack trace object in Ruby; not to print it, just to get it to do some recording and dumping for later analysis. Is that possible? How?

Answer

Sven Koschnicke picture Sven Koschnicke · Sep 30, 2010

You can use Kernel.caller for this. The same method is used when generating stack traces for exceptions.

From the docs:

def a(skip)
  caller(skip)
end
def b(skip)
  a(skip)
end
def c(skip)
  b(skip)
end
c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
c(2) #=> ["prog:8:in `c'", "prog:12"]
c(3) #=> ["prog:13"]