Home Back Play Pinja Bobbity flop

The Ruby BrainFuck Interpreter

Copyright © Stephen Sykes, 2001.

This is an implementation of the BrainFuck language in Ruby.

In case you haven't come across Ruby before, it is an extremely well designed object oriented programming language, which has a number of interesting features - to learn more visit the Ruby home page.

Personally, I prefer ETA to BrainFuck, but I was wondering if you could translate between the two. In fact, I think it would be possible to write a BrainFuck to ETA converter without too much trouble, but going the other way would be enormously difficult - the divide instruction would be particularly tricky I think.

A converter from to ETA would need to represent the array on the stack - meaning that at the start of the program you would need to place 30,000 zeros there, so your program would begin with 60k of ne instructions. Unless you invented some clever way of extending the stack as required. Of course, strict ETA interpreters that only have a 100 byte stack don't stand a chance anyway, but let's not worry about that.

I wrote this interpreter as a step to inventing a translation program, and it's here in case anyone needs it for anything, unlikely as that may seem.

Source Code

You can download the program here.
class Bf
def initialize
  @a=[0]*30000
  @b=[]
  @p=0
  @x=0
end

def r
  @p+=1 if !@j
end

def l
  @p-=1 if !@j
end

def i
  @a[@p]+=1 if !@j
end

def d
  @a[@p]-=1 if !@j
end

def o
  print @a[@p].chr if !@j
end

def n
  @a[@p] = $stdin.getc if !@j
end

def j
  @x+=1
  if @a[@p]==0
    @j=true
  else
    @b[@x]=$i-1
  end
end

def e
  if @j
    @j=false
  else
    $i=@b[@x]
  end
  @x-=1
end

def b
  10.times {|a| print @a[a].chr}
end
end

b=Bf.new
$i=0
p=$<.readlines.join.tr('^><+\-.,[]#','').tr('><+\-.,[]#', 'rlidonjeb')
while $i<p.size
  b.send(p[$i].chr)
  $i+=1
end



S.D.Sykes May 2001