Skip to content

Instantly share code, notes, and snippets.

@gunn
Last active December 17, 2015 22:29
Show Gist options
  • Save gunn/5682756 to your computer and use it in GitHub Desktop.
Save gunn/5682756 to your computer and use it in GitHub Desktop.
Just a tiny brainfuck implemetation in ruby
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