Created
January 13, 2009 01:49
-
-
Save faultier/46281 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# coding: utf-8 | |
module HQ9Plus | |
class Interpreter | |
NAME = 'RHQ9+' | |
attr_accessor :interactive | |
def initialize | |
@acum = 0 | |
@source = '' | |
@interactive = false | |
end | |
def run(source) | |
@source << source.upcase | |
source.each_char do |c| | |
executed = case c | |
when /H/i then print_hello | |
when /Q/i then print_source | |
when /9/i then print_99bottles | |
when /\+/ then increment | |
end | |
puts "# @acum => #{@acum}, @source => #{@source.gsub(/[^HQ9\+]/,'')}" if executed && @interactive | |
end | |
end | |
private | |
def print_hello | |
puts 'Hello, World!' | |
true | |
end | |
def print_source | |
puts @source | |
true | |
end | |
def print_99bottles | |
a = 'Bottle';b = 'of beer';c = 'on the wall' | |
buff = '' | |
99.downto(1) do |i| | |
ex = i > 1 ? 's' : '' | |
buff << "#{i} #{a}#{ex} #{b} #{c}, #{i} #{a}#{ex} #{b}.\nTake one down and pass it around, #{i-1} #{a}#{ex} #{b} #{c}.\n\n" | |
end | |
puts buff | |
true | |
end | |
def increment | |
@acum += 1 | |
true | |
end | |
end | |
end | |
if $0 == __FILE__ | |
$0 = File.basename($0) | |
interpreter = HQ9Plus::Interpreter.new | |
source = case | |
when ARGV.size == 2 && ARGV[0] == '-e' | |
unless ARGV[1].length > 0 | |
$stderr.puts 'abort!' | |
$stderr.puts "usage: #{$0} -e CODE" | |
exit(1) | |
end | |
ARGV[1] | |
when ARGV.size == 1 && (ARGV[0] == '-i' || ARGV[0] == '--interactive') | |
interpreter.interactive = true | |
loop do | |
print 'irhq9p> ' | |
cmd = $stdin.gets | |
if cmd =~ /E/i | |
puts 'Bye!' | |
break | |
end | |
interpreter.run(cmd) | |
end | |
else gets | |
end | |
interpreter.run(source) if !!source | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment