Execute Brain****/Ruby

From Rosetta Code
Revision as of 20:29, 21 July 2009 by rosettacode>Glennj (add Ruby)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Execute Brain****/Ruby is an implementation of Brainf***. Other implementations of Brainf***.
Execute Brain****/Ruby is part of RCBF. You may find other members of RCBF at Category:RCBF.

More effort could be made to read a program from a file or from stdin. <lang ruby>class RCBF

 def initialize(program)
   @d = [0] * 30_000
   @program = program
 end
 def run
   dc = 0
   pc = 0
   while pc < @program.length
     print [pc, @program[pc].chr].inspect if $DEBUG
     case @program[pc]
     when ?> 
       dc += 1
       print "\t#{dc}" if $DEBUG
     when ?< 
       dc -= 1
       print "\t#{dc}" if $DEBUG
     when ?+ 
       @d[dc] += 1
       print "\t#{dc},#{@d[dc]}" if $DEBUG
     when ?- 
       @d[dc] -= 1
       print "\t#{dc},#{@d[dc]}" if $DEBUG
     when ?. 
       print "\t#{dc},#{@d[dc]}\t" if $DEBUG
       print @d[dc].chr
     when ?, then
       @d[dc] = $stdin.getc
       print "\t#{dc},#{@d[dc]}" if $DEBUG
     when ?[ then
       if @d[dc] == 0
         pc += 1 while @program[pc] != ?]
         p "  #{[pc,@program[pc].chr].inspect}" if $DEBUG
       end
     when ?] then
       if @d[dc] != 0
         pc -= 1 while @program[pc] != ?[
         p "  #{[pc,@program[pc].chr].inspect}" if $DEBUG
       end
     end
     puts if $DEBUG
     pc += 1
   end
 end

end</lang> Test:

irb(main):048:0> helloworld = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.'
=> "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
irb(main):049:0> bf = RCBF.new(helloworld)
=> #<RCBF:0x7ff537d0 @d=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
...
irb(main):050:0> bf.run
Hello World!
=> nil