Execute HQ9+/Ruby: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Categorization now in master page)
m (make dispatch table a class constant)
Line 2: Line 2:
This [[Ruby]] program implements an [[HQ9+]] interpreter.
This [[Ruby]] program implements an [[HQ9+]] interpreter.
<lang ruby>class HQ9plus
<lang ruby>class HQ9plus
Dispatch = Hash.new(:unknown).merge({
'h' => :hello,
'q' => :quine,
'9' => :beer,
'+' => :accumulate
})

def initialize(opts={})
def initialize(opts={})
@program = if opts[:program] then opts[:program]
@program = if opts[:program] then opts[:program]
elsif opts[:filename] then File.read(opts[:filename])
elsif opts[:filename] then File.read(opts[:filename])
else ''
else ''
end
end
@accumulator = 0
@accumulator = 0
end
end
Line 12: Line 19:


def run
def run
@program.downcase.each_char {|char| self.send Dispatch[char]}
dispatch = Hash.new(:unknown)
dispatch['h'] = :hello
dispatch['q'] = :quine
dispatch['9'] = :beer
dispatch['+'] = :accumulate

@program.downcase.each_char do |char|
self.send dispatch[char]
end
end
end



Revision as of 14:17, 31 December 2009

Execute HQ9+/Ruby is an implementation of HQ9+. Other implementations of HQ9+.
Execute HQ9+/Ruby is part of RCHQ9+. You may find other members of RCHQ9+ at Category:RCHQ9+.

This Ruby program implements an HQ9+ interpreter. <lang ruby>class HQ9plus

 Dispatch = Hash.new(:unknown).merge({
     'h' => :hello, 
     'q' => :quine, 
     '9' => :beer, 
     '+' => :accumulate
 })
 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
   @program.downcase.each_char {|char| self.send Dispatch[char]}
 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