How to get a backtrace from a SystemStackError: stack level too deep?

Viewed 15551

Often I get hard to debug infinite recursions when coding ruby. Is there a way to get a backtrace out of a SystemStackError to find out, where exactly the infinite loop occurs?

Example

Given some methods foo, bar and baz which call each other in a loop:

def foo
  bar
end

def bar
  baz
end

def baz
  foo
end

foo

When I run this code, I just get the message test.rb:6: stack level too deep (SystemStackError). It would be useful to get at least the last 100 lines of the stack, so I could immediately see this is a loop between foo, bar and baz, like this:

test.rb:6: stack level too deep (SystemStackError)
  test.rb:2:in `foo'
  test.rb:10:in `baz'
  test.rb:6:in `bar'
  test.rb:2:in `foo'
  test.rb:10:in `baz'
  test.rb:6:in `bar'
  test.rb:2:in `foo'
  [...]

Is there any way to accomplish this?

EDIT:

As you may see from the answer below, Rubinius can do it. Unfortunately some rubinius bugs prevent me from using it with the software I'd like to debug. So to be precise the question is:

How do I get a backtrace with MRI (the default ruby) 1.9?

8 Answers
Related