title: objects .each method in ruby, lets me read values from object, but won't let me write values to it. Scoping issue?
body: <p>So I wrote a 2D array class for a project I'm working on, in Ruby.</p>
  
  <p>It's simple enough: the <code>initialize</code> creates a Square 2D array, of a size dictated by its argument, called <code>@contents</code>.</p>
  
  <p>I overload the <code>[]</code> operator to make the data within the object accessible, like so:</p>
  
  <pre><code>def [] (x, y)
    @contents[x][y]
  end
  
  def []=(x, y, z)
    @contents[x][y] = z
  end
  </code></pre>
  
  <p>I add an <code>each</code> method to it, so that I could mix in the enumerable module, and give it some functionality, like so:</p>
  
  <pre><code>def each
    i, j =0,0
    while (i&lt;@size)
      while(j&lt;@size)
        yield @contents[i][j]
        j+=1
      end
      i, j = i+1, 0
    end
  end
  </code></pre>
  
  <p>and I gave it a <code>to_s</code> method, like so:</p>
  
  <pre><code>def to_s
    @contents.each{|i| puts i}
  end
  </code></pre>
  
  <p>Now, I create a new instance of this 2D array object in a new file, and try to populate it. Initally,I did this manually, with nested loops, like so:</p>
  
  <pre><code>j, i, k= 0, 0, 0
  puts " size = #{@size}"
  while (i&lt;@size)
    while(j&lt;@size)
      @2Darray[i,j], k, j= @array[k], k+1, j+1
    end
    i, j=i+1, 0
  end
  </code></pre>
  
  <p>And that works just fine. the to_s method will print out the array perfectly. I realized though, that these nested loops might not have been the 'ruby way' and tried to do it with itterators. I had already implimented an <code>each</code> method, so I tried to subsitute the above, with the following:</p>
  
  <pre><code>j=0
  @2Darray.each{|i|
    i = @array[j]
    j += 1
    break unless j &lt; size
  }
  </code></pre>
  
  <p>But, unfortunately, this doesn't work. It runs just fine, but when the to_s is called, it prints line after line of nothing. ie, it prints out an array of empty arrays.</p>
  
  <p>I thought it was my .each method, but that works fine when the to_s method calls it. I thought it might have been my <code>[]=</code> method, but that works fine when I use nested while-loops.</p>
  
  <p>Now I'm thinking it must be a problem with scoping. in my each-loop above, <code>|i|</code> is a local variable, am I right? So that I assign the value of <code>array[j]</code> to <code>i</code>, but i is just a copy of the (empty) position which I want to fill, yes?</p>
  
  <p>So, firstly, am I on the right track, or is my problem somewhere else entirely? If so, where, if not: How can I modify my each-loop above, to make assignments to the data within @2Darray, instead of just changing the value of the <code>|i|</code> place-holder.</p>
  
  <p>Apologies for my verbouseness, and thank you for your time! Any help would be appreciated.</p>