title: Substitute all matches with values in Ruby regular expression
body: <p>I'm having a problem with getting a Ruby string substitution going. I'm writing a preprocessor for a limited language that I'm using, that doesn't natively support arrays, so I'm hacking in my own.</p>
  
  <p>I have a line:</p>
  
  <pre><code>x[0] = x[1] &amp; x[1] = x[2]
  </code></pre>
  
  <p>I want to replace each instance with a reformatted version:</p>
  
  <pre><code>x__0 = x__1 &amp; x__1 = x__2
  </code></pre>
  
  <p>The line may include square brackets elsewhere.</p>
  
  <p>I've got a regex that will match the array use:</p>
  
  <pre><code>array_usage = /(\w+)\[(\d+)\]/
  </code></pre>
  
  <p>but I can't figure out the Ruby construct to replace each instance one by one. I can't use <code>.gsub()</code> because that will match every instance on the line, and replace every array declaration with whatever the first one was. <code>.scan()</code> complains that the string is being modified if you try and use scan with a <code>.sub()!</code> inside a block.</p>
  
  <p>Any ideas would be appreciated!</p>