# # http://stackoverflow.com/questions/824562/does-ruby-perform-tail-call-optimization # See also: # http://nithinbekal.com/posts/ruby-tco/ # and http://blog.tdg5.com/tail-call-optimization-in-ruby-deep-dive/ # source = <<-SOURCE def fact n, acc = 1 if n.zero? acc else fact n - 1, acc * n end end fact 100000 SOURCE # This should print a very large number. If you don't set TCO option # to true, you should get the "stack too deep" error. i_seq = RubyVM::InstructionSequence.new source, nil, nil, nil, tailcall_optimization: true, trace_instruction: false # ^^^^^^^^^^^^^^^^^^^^^^^^^^^ # Indeed, prints "#" for 2.0--2.2 for 10,000 # For 2.3, prints the result 10,000 anyway, but for 100,000 # also runs out of stack. Just # Uncomment this to see bytecode: puts i_seq.disasm begin value = i_seq.eval p value rescue SystemStackError => e p e end