I recently wrote a simple Brainfuck interpreter in Ruby:
require "io/console"
$VALID = "+-<>.,"
def parse(code, level=0)
ast = []
while !code.empty? do
c = code.shift
if c == "]" then
if level == 0 then
throw Exception.new "Unmatched brackets"
else
return ast
end
end
if c == "[" then
ast.push parse(code, level+1)
elsif $VALID.include? c then
ast.push c
end
end
if level != 0 then
throw Exception.new "Unmatched brackets"
end
ast
end
class BF
def initialize
@tape = Array.new 3e4, 0
@ptr = 3e4.to_i / 2
end
def run(ast)
ast.each {|e|
if e.kind_of? Array then
while @tape[@ptr] != 0 do
self.run e
end
else
case e
when "+"
@tape[@ptr] += 1
when "-"
@tape[@ptr] -= 1
when ">"
@ptr += 1
when "<"
@ptr -= 1
when "."
STDOUT.write @tape[@ptr].chr
when ","
@tape[@ptr] = STDIN.getch.ord
end
@tape[@ptr] &= 0xFF
end
}
end
end
if ARGV[0] == nil then
puts "Simple BrainFuck interpreter"
puts "Usage: #{$0} <file>"
exit 1
end
bf = BF.new
bf.run parse(File.read(ARGV[0]).chars)
I am pretty bad at Ruby, can someone review this?