Class: Brainfuckrb::Brainfuck
- Inherits:
-
Object
- Object
- Brainfuckrb::Brainfuck
- Defined in:
- lib/brainfuckrb.rb
Instance Method Summary collapse
- #_run(stop = nil) ⇒ Object
-
#initialize(program) ⇒ Brainfuck
constructor
A new instance of Brainfuck.
- #reset ⇒ Object
- #run(stop = nil) ⇒ Object
Constructor Details
#initialize(program) ⇒ Brainfuck
Returns a new instance of Brainfuck.
7 8 9 10 |
# File 'lib/brainfuckrb.rb', line 7 def initialize(program) @program = program reset end |
Instance Method Details
#_run(stop = nil) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/brainfuckrb.rb', line 25 def _run(stop = nil) stop ||= @program.length while @pc < stop case @program[@pc].chr when ">" then @p += 1 when "<" then @p -= 1 when "+" then @mem[@p] += 1 when "-" then @mem[@p] -= 1 when "." then STDOUT.putc @mem[@p].chr when "," then @mem[@p] = STDIN.readchar.ord when "[" depth = 1 start = _end = @pc while depth != 0 _end += 1 depth += 1 if @program[_end] == "[" depth -= 1 if @program[_end] == "]" end while @mem[@p] != 0 @pc = start + 1 _run(_end) end @pc = _end when "]" then raise "x:y: not expecting \']\'" end @pc += 1 end end |
#reset ⇒ Object
12 13 14 15 16 |
# File 'lib/brainfuckrb.rb', line 12 def reset @mem = [0] * 65535 @p = 0 @pc = 0 end |
#run(stop = nil) ⇒ Object
18 19 20 21 22 23 |
# File 'lib/brainfuckrb.rb', line 18 def run(stop = nil) _run(stop) result = @mem[@p] reset return result end |