Bob Nadler, Jr. Bob Nadler, Jr.

Ruby's Matrix

Published over 13 years ago 1 min read

The Game of Life

I attended a Code Retreat a few weeks ago where the exercise was to implement Conway's Game of Life. The Code Retreat was awesome and I definitely recommend you check one out. I wasn't familiar with the Game of Life before attending so afterwards I decided to play around with different ways of implementing it.

I won't do into the mechanics of the game here, but one of the ways to implement the game is to use a two-dimensional array to represent the game "board". The heart of the game's decision engine revolves around figuring out the neighboring values of individual cells in the array. My first thought when I looked at it was that the game board is just a matrix, and the neighboring cell values can be determined by extracting a sub-matrix centered around the cell I'm looking at.

StdLib FTW

Since I'm doing this in Ruby, I decided to look around to see if there were any gems that implemented basic matrices. After a little digging, I found out that Ruby's standard library already has a Matrix class! The Matrix class has two methods that I'm interested in, the first Matrix#minor will give me a sub-matrix. The second, Matrix#to_a, converts a matrix to an array, which can easily be summed.

Matrix Mixing

I decided to write a matrix extension module that will be mixed into the Matrix class. Here's the code:

Using these methods allows me to implement the game board as a matrix and leverage the standard library. I've put up a full Ruby implementation of the game on Github.


Share This Article