fork(3) download
  1. require 'stringio'
  2.  
  3. class HelloWorld
  4.  
  5. def self.interpret(**kwargs)
  6. new(**kwargs).interpret
  7. end
  8.  
  9. def initialize(input: STDIN, output: STDOUT)
  10. @accumulator = 1
  11. @stack = []
  12. @input = input
  13. @output = output
  14. end
  15.  
  16. def interpret(input = @input)
  17. input.each_char do |c|
  18. puts(" => %c: %p (%i)" % [c, @stack, @accumulator]) if ENV['VERBOSE']
  19. case c
  20. when 'c'
  21. @stack.push('' << (@stack.pop || ''))
  22. when 'h'
  23. @stack.push(get_user_input)
  24. when 'e'
  25. @stack.push(@stack.pop.to_i)
  26. when 'l'
  27. @stack.push(@stack.first)
  28. when 'o'
  29. x = @stack.pop
  30. if @looping && x == 0
  31. raise StopIteration
  32. elsif !@looping
  33. @looping = true
  34. branch = input.gets('o')
  35. loop{interpret(StringIO.new(branch))} rescue StopIteration
  36. @looping = false
  37. else
  38. @stack.push(@stack.last)
  39. end
  40. when ','
  41. @stack.push(@accumulator += 1)
  42. when '.'
  43. @stack.push(@accumulator -= 1)
  44. when ' '
  45. raise StopIteration if @stack.first == @accumulator
  46. when 'w'
  47. x = @stack.pop
  48. y = @stack.pop
  49. @stack.push(y % x)
  50. when 'm'
  51. x = @stack.pop
  52. y = @stack.pop
  53. @stack.push(x % y)
  54. when 'r'
  55. @stack.push(@stack.pop == 0 ? 1 : 0)
  56. when 'd'
  57. @stack.push(@stack.pop == 0 ? "false\n" : "true\n")
  58. when '!'
  59. @output.print @stack.pop
  60. return(0) if @stack.pop == 0
  61. when '0'..'9'
  62. x = @stack.pop
  63. if x.is_a?(Numeric) && x != 0
  64. @stack.push(x*10 + c.to_i)
  65. else
  66. @stack.push(x) if x
  67. @stack.push(c.to_i)
  68. end
  69. end
  70. end
  71. unless @looping
  72. raise 'Unexpected end of input. Please end programs with "!"'
  73. end
  74. end
  75.  
  76. def get_user_input
  77. ARGV.shift || gets.chomp
  78. end
  79.  
  80. end
  81.  
  82. input = "hello, worl!"
  83.  
  84. if input.nil?
  85. loop{HelloWorld.interpret(input: StringIO.new(gets))}
  86. else
  87. HelloWorld.interpret(input: StringIO.new(input))
  88. end
Success #stdin #stdout 0.06s 9872KB
stdin
233
stdout
233