Main

This is ChaosR's page

About

-

CV/Resume

-

Ruby Brainfuck

This is my Ruby brainfuck interpreter.


raise "No file specified"    unless ARGV[0]
raise "File does not exist"  unless File.exists?(ARGV[0])
raise "File is not readable" unless File.readable?(ARGV[0])
file = File.open(ARGV[0])

cells    = Array.new(30000, 0)
min_size = 0
max_size = 255
location = 0

while not file.eof?
  char = file.getc
  case char
    when ?>
      location += 1 if location < size
    when ?<
      location -= 1 if location > 0
    when ?+
      cells[location] += 1
      cells[location] = min_size if cells[location] > max_size
    when ?-
      cells[location] -= 1
      cells[location] = max_size if cells[location] < min_size
    when ?.
      $stdout.putc cells[location]
    when ?,
      cells[location] = $stdin.getc
    when ?[
      if cells[location] == 0
        nested = 1
        begin
          _char = file.getc
          nested += 1 if _char == ?[
          nested -= 1 if _char == ?]
        end until nested == 0
      end
    when ?]
      if cells[location] != 0
        nested = 1
        begin
        file.pos = file.pos - 2
          _char = file.getc
          nested += 1 if _char == ?]
          nested -= 1 if _char == ?[
        end until nested == 0
      end
  end
end