Execute HQ9+/Ruby

From Rosetta Code
Revision as of 17:08, 21 July 2009 by rosettacode>Glennj (add Ruby)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Execute HQ9+/Ruby is part of RCHQ9+. You may find other members of RCHQ9+ at Category:RCHQ9+.

<lang ruby>class HQ9plus

 def initialize(opts={})
   @program =  if    opts[:program] then opts[:program]
               elsif opts[:filename] then File.read(opts[:filename])
               else  
               end
   @accumulator = 0
 end
 attr_reader :accumulator
 def run
   methods = Hash.new(:unknown)
   methods['h'] = :hello
   methods['q'] = :quine
   methods['9'] = :beer
   methods['+'] = :accumulate
   @program.downcase.each_char do |char|
     send methods[char]
   end
 end
 def hello
   puts "Hello, world!"
 end
 def quine
   puts @program
 end
 def beer
   puts '99 bottles here ...'
 end
 def accumulate
   @accumulator += 1
 end
 def unknown
   # do nothing
 end

end

hq9 = HQ9plus.new(:program => '+qhp;+9Q') hq9.run puts hq9.accumulator</lang>

Output:

+qhp;+9Q
Hello, world!
99 bottles here ...
+qhp;+9Q
2