I'm still getting to grips with Ruby, but I think I'm doing well. My
last post generated a lot of positive comments/advice which really
helped me, so I thought I'd post some more of my code to try and repeat
that!

The following is a method which will convert an infix expression (1+1)
to a postfix expression (1 1 +). It expects a string and returns an
array. Once again I'd really appreciate your comments.

def postfix(expression)

  precedence = {nil=>0,40=>0,42 =>2, 43=>1, 45=>1,47=>2}

  output = Array.new
  stack = Array.new
  temp = ''

  expression.each_byte do |asc|

    case asc
      when 41
        output.push(temp)
        temp = ''
        loop{
          if stack.empty? == false
            popped = stack.pop
            if popped == 40
              break
            else
              output.push(popped.chr)
            end
          else
            raise 'Missing "("!'
          end
        }
      when 40,42, 43, 45, 47 #*+-/
        output.push(temp)
        temp = ''
        unless asc == 40
          p_asc = precedence[asc]
          loop{
            if  (p_asc > precedence[stack.last])
              break
            else
              output.push(stack.pop.chr)
            end
          }
        end
        stack.push(asc)
      else
        temp += asc.chr
    end
  end
  stack.each{|asc| output.push(asc.chr)}
  !output.include?('(') or raise 'Missing ")"!'
  output.delete('')
  output
end

-- 
Posted via http://www.ruby-forum.com/.