Created
July 24, 2015 05:03
-
-
Save dyama/670ba6cd3b9e4401412c to your computer and use it in GitHub Desktop.
Ruby brainfuck interpretor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-. | |
------------.<++++++++.--------.+++.------.--------.>+. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment