Skip Navigation

Tail Call Optimization

I wasn't able to find any up-to-date information about tail call optimization support in Ruby, so I decided to post this hoping that it will pop up next time someone might also be searching for this topic... What I was able to figure out is that TCO can be enabled in Ruby 3.4 via a compile option like so:

 ruby
RubyVM::InstructionSequence.compile_option = {tailcall_optimization: true}

def tailSumUntil(n, m)
  n == 0 ? m : tailSumUntil(n - 1, n + m)
end

tailSumUntil(100_000_000, 0)
# => 5000000050000000

Comments