中置記法から後置記法(逆ポーランド記法)への変換

逆ポーランド記法への変換2(2009.12.08)の下の方にある図を参考に Ruby でコーディングしてみた。
中置の +, -, *, / を実装。前置の - は実装してない。

# infix notation to postfix notation
# refer to http://www.gg.e-mansion.com/~kkatoh/program/novel2/novel208.html
def ifn2pfn ifn
  i = 0
  stack = []
  pfn = ""
  while i < ifn.size
    c = ifn[i].chr
    if c == " "
      i += 1
    elsif c =~ /[0-9]/
      c << ifn[i] while ifn[i+=1] =~ /[0-9]/
      pfn << c + " "
    elsif c == ")"
      until (s = stack.pop) == "("
        pfn << s + " "
      end
      i += 1
    elsif c == "("
      stack.push c
      i += 1
    else
      if stack.empty?
        stack.push c
      else
        if c =~ /[-\+]/
          until stack.empty?
            s = stack.pop
            if s =~ /[\*\/]/
              pfn << s + " "
            else
              stack.push s
              break
            end
          end
        end
        stack.push c
      end
      i += 1
    end
  end
  until stack.empty?
    pfn << stack.pop + " "
  end
  pfn.chop
end

2009.12.09 バグ発見
"2/4+1" でおかしくなる。
2009.12.10 修正