Ribitco: Noddy runtime TCO for Ruby

So, I wrote my first RubyGem recently. It provides a class macro that allows you to tail-call optimise methods at runtime. Please note that this was just a bit of fun and I realise there are corner cases. The source code is available here.


Add this line to your application's Gemfile:

gem 'ribitco'

And then execute:

$ bundle

Or install it yourself as:

$ gem install ribitco

This Code

require 'ribitco'

class Recursive

  def factorial(n, acc=1)
    if n < 2 then acc else factorial(n - 1, n * acc) end

  include Ribitco::TailCallOptimiser
  tco :factorial


class Recursive

  define_method :factorial do |n, acc = 1|
    (n < 2) ? (acc) : (n = (n - 1); acc = (n * acc); redo)


No Stack Explosion

example = Recursive.new
puts example.factorial(10000) # => 284625968091705451890641321211986889014805140170...
This entry was posted in News. Bookmark the permalink.

Comments are closed.