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?
For Ruby 2.0+, you can use
Kernel#caller_locations. It is essentially the same as
Kernel#caller (covered in Sven Koschnicke's answer), except that instead of returning an array of strings, it returns an array of
Thread::Backtrace::Location provides methods such as
base_label, which may be useful when you need access to specific details about the stack trace, and not just a raw string.
From the docs:
Returns the current execution stack—an array containing backtrace location objects.
Thread::Backtrace::Location for more information.
The optional start parameter determines the number of initial stack entries to omit from the top of the stack.
A second optional
length parameter can be used to limit how many
entries are returned from the stack.
start is greater than the size of current execution
Optionally you can pass a range, which will return an array containing the entries within the specified range.
def a caller_locations(0) end def b a end def c b end c.map(&:base_label) #=> ["a", "b", "c", "<main>"]