Clean 2D Arrays in Ruby

    I've recently found myself needing a simple and clean way to handle
2D arrays in ruby, so I created a Matrix class for that purpose. It's certainly not abiding by a lot of ruby style guidelines, but it's the cleanest way I can think of to handle 2D arrays.

# Simple matrix class for applications that need 2-dimensonal arrays
class Matrix
  # Creates a new matrix, and may initialize it with an array
  def initialize(array=[])
    @matrix = array
  end
  # Retrieves a row from the matrix, will also set the value of a row
  # if a block is passed
  def row(_row, &block)
    if block_given?
      @matrix[_row] = block.call
    else
      @matrix[_row]
    end
  end
  # Retrieves a specific cell from the matrix
  def [](_row, _column)
    @matrix[_row][_column]
  end
  # Sets the value for a cell in the matrix
  def []=(_row, _column, value)
    @matrix[_row][_column] = value
  end
  # Appends a row to the matrix
  def <<(_row)
    @matrix << _row
  end
end
 
# Helper class to create matrixes
class M
  def self.[](*rows)
    array = []
    rows.each do |row|
      array << row
    end
    Matrix.new(array)
  end
end

So, sample usage would be along these lines:
matrix = 
M[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix[0, 0] => 1
matrix[4, 0] = 10

It doesn't do a whole lot, but it's at least cleaner than a standard array of arrays (if only by a little)

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

murphy

What about the built-in Matrix class? http://www.ruby-doc.org/stdlib/libdoc/matrix/rdoc/index.html

snuxoll's picture

I feel like a tard for having

I feel like a tard for having not checked the standard library documentation now.

Stefan Nuxoll

Also quite funny, dreamhost

Also quite funny, dreamhost happily installed mod_rack, but why are they using php via CGI and not mod_php, I'm utterly confused. It would shrink memory usage on their servers by a ton, make hosted sites more responsive, and probably lighten CPU load too.

Stefan Nuxoll

unlocked cell phone

gucci

Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://www.oneor-more.com/

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options