Class: Esolang::Interpreters::Brainfuck

Inherits:
BaseInterpreter show all
Defined in:
lib/interpreters/brainfuck_interpreter.rb

Overview

The Brainfuck class represents an interpreter for the Brainfuck esoteric programming language.

Direct Known Subclasses

Ook

Instance Method Summary collapse

Constructor Details

#initialize(code, input = '') ⇒ Brainfuck

Initializes a new instance of the Brainfuck interpreter.

Parameters:

  • code (String)

    The Brainfuck code to interpret.

  • input (String) (defaults to: '')

    The input for the Brainfuck program (optional).



13
14
15
16
17
18
19
# File 'lib/interpreters/brainfuck_interpreter.rb', line 13

def initialize(code, input = '')
  # Added ? to valid chars for compatibility with Ook! But don't parse ? in Brainfuck
  super(code.gsub(/[^\?,\.<>\+-\[\]]/, ''))
  @input = chars_to_bytes(input)
  @output = []
  @tape = Hash.new(0)
end

Instance Method Details

#runString

Executes the interpretation of the Brainfuck code.

Returns:

  • (String)

    The result of the Brainfuck interpretation.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/interpreters/brainfuck_interpreter.rb', line 24

def run
  while running? do
    case command
    when ',' then input_to_tape
    when '.' then tape_to_output_array
    when '>' then move_right
    when '<' then move_left
    when '+' then increment
    when '-' then decrement
    when '[' then loop_begin
    when ']' then loop_end
    end

    @code_pointer += 1
  end

  translate_output_bytes_to_chars
end