Implemeting HQ9+ in 10 lines of Ruby

HQ9+ is a excessively simple esoteric programming language. It has only four commands:
H: Print “Hello, World!”
Q: Prints the contents of the program onto the screen
9: Print the canonical lyrics of the song, “99 bottles of beer”.
+: Increment the accumulator

Here’s the entire implementation:

1
2
3
4
5
6
7
8
9
10
def hq9(src)
  src.downcase.split('').each do |i|
    case i
      when 'h'; puts "Hello, World!"
      when 'q'; puts src
      when '9'; 99.downto(0) { |b| puts "#{b==0?'No more b':"#{b} B"}ottle#{'s'if b!=1} of beer on the wall, #{b==0?'No more':b} bottle#{'s'if b!=1} of beer.#{b==0?"nGo to the store and buy some more, 99 bottles of beer on the wall.":"nTake one down and pass it around, #{b-1} bottle#{'s'if b!=2} of beer on the wall.nn"}" }
      when '+'; $i = $i ? $i + 1 : 0;
    end
  end
end

Note: I got the lyric printing code from here.

Tags: , , ,

One Response to “Implemeting HQ9+ in 10 lines of Ruby”

  1. [...] An implementation of the HQ9+ programming language. It is very simple to do and will give you a good idea of flow control. [...]

Leave a Reply