Representing a long regular expression in a Polynomial class
Rather than construct the polynomial string incorrectly, then fix it with regex's, it may be easier to contruct it directly.  This is one way you could do that.

class Polynomial
  def initialize(coefficients)
    @coefficients = coefficients
  end

  def to_s
    coeffs = @coefficients.each_with_index.select { |c,k| c.nonzero? || k==0 }.reverse
    coeffs.each_with_object('') do |(c,k), s|
      cneg = (c.to_f &lt; 0.0)
      if [c,k] == coeffs.first
        s &lt;&lt; '-' if cneg
      else
        s &lt;&lt; (cneg ? ' - ' : ' + ')
      end
      s &lt;&lt; "#{c.abs}" unless (c.abs.to_f == 1.0 &amp;&amp; k &gt; 0)
      s &lt;&lt; "x" if k &gt; 0
      s &lt;&lt; "^#{k}" if k &gt; 1
    end
  end
end                   

coefficients = [2.1, 3, 1.0, 0, -6.1, 1, -5.3, 0.2]
p Polynomial.new(coefficients).to_s
  # =&gt; 0.2x^7 - 5.3x^6 + x^5 - 6.1x^4 + x^2 + 3x + 2.1


For this example value of coefficients, this is what's happening:

First save each coeffient's index with its value:

a = @coefficients.each_with_index
  # =&gt; [[2.1,0], [3,1], [1.0,2], [0,3], [-6.1,4], [1,5], [-5.3,6], [0.2,7]] 


Next, select only pairs for which the value is non-zero or the exponent is zero:

b = a.select { |c,k| c.nonzero? || k==0 }
  # =&gt; [[2.1, 0], [3, 1], [1.0, 2], [-6.1, 4], [1, 5], [-5.3, 6], [0.2, 7]]


Notice that [0,3] has been removed.  Now reverse the elements of the array:  

coeffs = b.reverse
  # =&gt; [[0.2, 7], [-5.3, 6], [1, 5], [-6.1, 4], [1.0, 2], [3, 1], [2.1, 0]]


each_with_object('') creates an empty string, designated s in the block.  It is then a simple matter to consider each element of each term in the polynomial to build up the string.

I'm not certain if I followed the formatting rules exactly, but if I did not, it should be easy to modify the code to conform.

(Edited to fix boo-boos spotted by @200_success.)