title: Swapping either Columns or Rows in a Ruby Matrix
body: <p>I want to swap either rows or columns in an array of arrays (i.e. a matrix). I have found this swap method online, and I extended it with my <code>mutate</code> function, where the <code>board.matrix</code> is the array of arrays:</p>
  
  <pre><code># Swap to elements of an Array
  def swap!(a,b)
    self[a], self[b] = self[b], self[a]
    self
  end
  
  def mutate(board)
    matrix = board.matrix
    random = rand
    rand_a = rand(matrix.length-1)
    rand_b = rand(matrix.length-1)
  
    puts "Old one:"
    board.print_matrix
    # We have a 50:50 chance of swapping either columns or rows
    if random &lt;= 0.5
      # Swap columns: Transpose first
      puts "Swapping columns #{rand_a} and #{rand_b}..."
      temp = matrix.transpose
      temp.swap!(rand_a, rand_b)
      matrix = temp.transpose
    else
      # Just swap rows
      puts "Swapping rows #{rand_a} and #{rand_b}..."
      matrix.swap!(rand_a, rand_b)
    end
    puts "New one:"
    board.print_matrix
  end
  </code></pre>
  
  <p>Now it does what it should for rows:</p>
  
  <pre><code>Old one:
  X  X  0  0  
  0  0  0  0  
  X  X  0  0  
  0  0  0  0  
  
  Swapping rows 1 and 0...
  New one:
  0  0  0  0  
  X  X  0  0  
  X  X  0  0  
  0  0  0  0
  </code></pre>
  
  <p>But it doesn't for columns. Why is that?</p>
  
  <pre><code>Old one:
  0  X  X  0  
  0  0  X  0  
  X  0  0  0  
  0  0  0  0  
  
  Swapping columns 1 and 0...
  New one:
  0  X  X  0  
  0  0  X  0  
  X  0  0  0  
  0  0  0  0
  </code></pre>