[ next ] [ prev ] [ contents ] [ skip to Untying the Knot ] [ up to Testing in a Matrix ] XP-Cinti TDD Workshop

Adding a Matrix

We will add a two dimensional array to our Net class.

# file: net.rb
class Net
  def initialize
    @tied = [
      [false, false, false, false, false],
      [false, false, false, false, false],
      [false, false, false, false, false],
      [false, false, false, false, false],
      [false, false, false, false, false],
    ]
  end

  def untied?(x,y)
    ! @tied[x][y]
  end

  def tie(x,y)
    @tied[x][y] = true
  end
end

Ruby Comments: Ruby uses the [...] notation to create literal Array objects. To create an array containing the integers 1, 2 and 3, all you need to write is... [1, 2, 3]

Our story requires a matrix of 5 columns and 5 rows. The [false, false, false, false, false] gives us one array of 5 booleans. Repeating that line 5 times gives us the entire array. There are probably better ways to do this, but this approach is the simplest for this size matix and we will stick with it for the moment. Doing this in the initialize method ensures that the matrix is created whenever a Net object is created. See Ruby Object Creation for more details on this process.

The only change required for the @tied variable is to add the [x][y] index operions to the variable usage.

In summary, to go from a single boolean to multiple required...

  • Creating the matrix and assigning it to @tied.
  • Adding [i] index operators wherever @tied was used.

And running our tests gives ...

  
$ ruby testnet.rb
Loaded suite testnet
Started...
....
Finished in 0.045223 seconds.
3 runs, 6 assertions, 0 failures, 0 errors


[ next ] [ prev ] [ contents ] [ skip to Untying the Knot ] [ up to Testing in a Matrix ] Copyright 2003 by Jim Weirich.
Some Rights Reserved