Execute HQ9+/Ruby: Difference between revisions

m
make dispatch table a class constant
m (Categorization now in master page)
m (make dispatch table a class constant)
Line 2:
This [[Ruby]] program implements an [[HQ9+]] interpreter.
<lang ruby>class HQ9plus
dispatchDispatch = Hash.new(:unknown).merge({
dispatch[ 'h'] => :hello,
dispatch[ 'q'] => :quine,
dispatch[ '9'] => :beer,
dispatch[ '+'] => :accumulate
})
 
def initialize(opts={})
@program = if opts[:program] then opts[:program]
elsif opts[:filename] then File.read(opts[:filename])
else ''
end
@accumulator = 0
end
Line 12 ⟶ 19:
 
def run
@program.downcase.each_char do {|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
 
Anonymous user