Execute HQ9+/Ruby: Difference between revisions
Content added Content deleted
m (make dispatch table a class constant) |
m (Fixed syntax highlighting.) |
||
(One intermediate revision by one other user not shown) | |||
Line 1: | Line 1: | ||
{{implementation|HQ9+}}{{collection|RCHQ9+}} |
{{implementation|HQ9+}}{{collection|RCHQ9+}} |
||
This [[Ruby]] program implements an [[HQ9+]] interpreter. |
This [[Ruby]] program implements an [[HQ9+]] interpreter. |
||
< |
<syntaxhighlight lang="ruby">class HQ9plus |
||
Dispatch = Hash.new(:unknown).merge({ |
Dispatch = Hash.new(:unknown).merge({ |
||
'h' => :hello, |
'h' => :hello, |
||
Line 45: | Line 45: | ||
hq9 = HQ9plus.new(:program => '+qhp;+9Q') |
hq9 = HQ9plus.new(:program => '+qhp;+9Q') |
||
hq9.run |
hq9.run |
||
puts hq9.accumulator</ |
puts hq9.accumulator</syntaxhighlight> |
||
Output: |
Output: |
Latest revision as of 10:21, 1 September 2022
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.
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
Output:
+qhp;+9Q Hello, world! 99 bottles here ... +qhp;+9Q 2