Saturday, January 31, 2009

Ruby: Adding the comparison operator (<=>) to the Symbol class

Hi guys/gals,

I'm working on some Ruby at the moment.
The code I'm writing uses hash maps and arrays to store word associations. To lower my memory usage, I decided to use symbols. Using symbols means all uses of the same word only use the one symbol worth of memory, instead of using a string worth of memory per word.

For example, 800 strings of "a", is a lot more usage than 800 symbols of :a, as the symbol is shared. If I used strings, I would have 800 independent copies of "a".

For display purposes, I wanted to sort my arrays of symbols. I soon learned that I could not call .sort! on an array of symbols. This is because the base class "Symbol" does not have <=> (comparison) operator by default. To be able to sort my arrays of symbols, I needed to add a <=> method to Symbol. The following code shows how to do this:

class Symbol
def <=> value
to_s <=> value.to_s

The code above injects a <=> (comparison) method into the Symbol class. The <=> method simply converts the symbols that it is comparing to strings, and then calls the string <=> method.

Note: I wrote the <=> method for my own purpose, to sort my symbols alphabetically. You could have just as easily written a method which compares symbols based on their length.

Ruby API: Symbol
Ruby API: String#Comparison

Monday, January 26, 2009


Hey guys/gals,

I have just spent the past long weekend on a coding binge, 20+ hours of lovely Ruby. The end result is a tower defence "game" with easy to use base classes, making it easy for anyone to add a level, a tower or even a new bullet type. The "game" is in a playable state, and anyone who his familiar with rubygame should check it out. The "game" is available via GIT.

The following is a screenshot of ruby-tower-defence in action: