Skip to content

Instantly share code, notes, and snippets.

@basicxman
Created May 16, 2011 16:28
Show Gist options
  • Select an option

  • Save basicxman/974775 to your computer and use it in GitHub Desktop.

Select an option

Save basicxman/974775 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Brainfuck Interpreter
class Runtime
def initialize(program)
@data = [0]
@data_ptr = 0
@inst_ptr = 0
@prog = parse(program)
run
end
def expand_array(arr, to_length)
arr += Array.new(to_length - arr.length, 0) if to_length > arr.length
end
def increment_data
@data[@data_ptr] = (@data[@data_ptr] <= 254) ? @data[@data_ptr] + 1 : 0
end
def decrement_data
@data[@data_ptr] = (@data[@data_ptr] >= 1) ? @data[@data_ptr] - 1 : 255
end
def increment_data_ptr
@data_ptr += 1
@data = expand_array(@data, @data.length + 1) if @data_ptr >= @data.length - 1
end
def decrement_data_ptr
@data_ptr -= 1
end
def output
print @data[@data_ptr].chr
end
def input
@data[@data_ptr] = STDIN.gets(1).ord
end
def loop_open
@inst_ptr = @prog[@inst_ptr+1..-1].rindex(']') if @data[@data_ptr] == 0
end
def loop_close
@inst_ptr = @prog[1..@inst_ptr].index('[') unless @data[@data_ptr] == 0
end
def method_missing(method_symbol)
case method_symbol.to_s
when '>' then increment_data_ptr
when '<' then decrement_data_ptr
when '+' then increment_data
when '-' then decrement_data
when '.' then output
when ',' then input
when '[' then loop_open
when ']' then loop_close
end
end
def parse(data)
@prog = data.gsub(/[^><+\-\.,\[\]]/, "").split(//)
end
def run
@inst_ptr = 0
until @inst_ptr == @prog.length
self.send(@prog[@inst_ptr])
@inst_ptr += 1
end
end
end
unless ARGV[0].nil?
if File.exists? ARGV[0]
interpreter = Runtime.new(File.read(ARGV[0]))
else
interpreter = Runtime.new(ARGV[0])
end
else
puts "No Brainfuck source file specified, aborting."
end
@rdebath
Copy link

rdebath commented Aug 10, 2014

Your loops are broken, this should be "Hello World!"

>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
->+++++++.<+[>[+>]>]<<<+++++++++++++++.>>.+++.------.--------.>>+.>++++.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment