On Nov 30, 2007 5:28 AM, Ruby Quiz <james / grayproductions.net> wrote: > This week's quiz is to write a script that translates postfix expressions into > the equivalent infix expression. Here's mine. It removes parenthesis, and handles all the binary operators in Ruby (unless I missed some). You can use a different set of operators and precedence rules by changing the $Operators hash. #postfix to infix # ruby quix #148 # Adam Shelly # # Converts postfix to infix notation # uses ruby's operators & precedence rules $Operators = { '&&'=>0, '||'=>0, '=='=>1, '==='=>1, '<=>'=>1, '<='=>2, '>='=>2, '<' =>2, '>'=>2, '^' =>3, '|' =>3, '&' =>4, '<<'=>5, '>>'=>5, '+' =>6, '-' =>6, '*' =>7, '/' =>7, '%'=> 7, '**'=>8, :term=>10 } class Term attr_reader :precedence def initialize str, groupPrec=nil @s = str @precedence = $Operators[str]||groupPrec||$Operators[:term] end def isOp @precedence != $Operators[:term] end def parenthesize @s="(#{@s})" end def to_s @s end end class Infix def initialize rpn stack=[] rpn.split.each do |t| term = Term.new(t) if term.isOp lval = stack.pop rval = stack.pop raise "Empty Stack" unless lval && rval lval.parenthesize if lval.precedence < term.precedence rval.parenthesize if rval.precedence < term.precedence phrase = "#{rval} #{term} #{lval}" tok = Token.new(phrase,term.precedence) # p term end stack.push term end @expr = stack.pop raise "Extra terms" unless stack.size==0 end def to_s @expr end end if __FILE__ == $0 puts Infix.new(ARGV.join(' ')).to_s end -Adam