Skip to content

Instantly share code, notes, and snippets.

@dyama
Created July 24, 2015 05:03
Show Gist options
  • Save dyama/670ba6cd3b9e4401412c to your computer and use it in GitHub Desktop.
Save dyama/670ba6cd3b9e4401412c to your computer and use it in GitHub Desktop.
Ruby brainfuck interpretor
#!/usr/bin/env ruby
# coding: utf-8
class Machine
RAMSIZE = 256
def initialize(file)
@ram = File.open(file).read.each_char.map.to_a
@eoc = @ram.size
@ram.fill(0, @eoc..RAMSIZE)
@p = @eoc
@pp = 0
end
def run
case @ram[@pp]
when '>'; @p += 1
when '<'; @p -= 1
when '+'; @ram[@p] += 1
when '-'; @ram[@p] -= 1
when '.'; putc @ram[@p]
when ','; @ram[@p] = stdin.readchar
when '['
if (@ram[@p] == 0)
while @ram[@pp] != ']'
@pp += 1
end
end
when ']'
if (@ram[@p] != 0)
while @ram[@pp] != '['
@pp -= 1
end
end
else
end
@pp += 1
end
def start
while true
self.run
break if @pp > @eoc
end
end
end
vm = Machine.new("./hello.bf")
vm.start
+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.
------------.<++++++++.--------.+++.------.--------.>+.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment