Last active
December 17, 2015 22:29
-
-
Save gunn/5682756 to your computer and use it in GitHub Desktop.
Just a tiny brainfuck implemetation in ruby
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
class BrainFuck | |
def initialize code | |
@code = code.gsub(/[^<>\[\]\+\-\.,]+/, "") | |
end | |
def run code | |
code = @code.split "" | |
tape = [] | |
c = t = 0 | |
while c != code.length | |
tape[t] ||= 0 | |
case code[c] | |
when "<" then t-=1 | |
when ">" then t+=1 | |
when "+" then tape[t]+=1 | |
when "-" then tape[t]-=1 | |
when "[" | |
if tape[t] == 0 | |
c += 1 while code[c] != "]" && c != code.length | |
end | |
when "]" | |
if tape[t] != 0 | |
c -= 1 while code[c] != "[" && c != 0 | |
end | |
when "." then print tape[t].chr | |
when "," then tape[t] = STDIN.getc.ord | |
end | |
c+=1 | |
end | |
end | |
end | |
BrainFuck.new(DATA.read).run if $0 == __FILE__ | |
__END__ | |
+++++ +++++ | |
[ | |
>,----- ----- ----- ----- ----- ----- --. | |
< - | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment