rpmohn / panix.com (Ross Mohn) writes:

> While reading data in from a file and populating a hash, I accidentally 
> added a key/val pair of nil/nil. All was fine until I tried to sort the 
> hash and got "NameError: undefined method `<=>' for nil". I know I should 
> check for nils before populating a hash, but it raises two questions in my 
> mind:
> 
> 1) Should nil be allowed as a Hash key? This does not make sense to me.
> 2) Maybe there should be a method defined for nil.<=> ? I think if it 
> always returned -1 it would be appropriate.

Perhaps the alternative questions might be: should you always be able
to sort a hash based on it's keys? I suspect the answer is "no".  For
example:

    h = { STDIN => 1, STDOUT => 2 }

    STDIN <=> STDOUT
    NameError: undefined method `<=>' for #<IO:0x401900a4>


Hash keys need only provide #hash and #eql?. There's no requirement for 
<=>, so in general you can't rely on being able to sort a hash.

You could always define a class SortableHash that verified that its
key objects supported #<=> before inserting them.

Back to 'nil' as a Hash key. I can't see any reason to forbid it
(although I believe older Rubys did). For example:

   namesOfObjects = { nil => 'nil', true => 'true', 1 => 'one' }

   namesOfObjects[nil]		# => "nil"

In terms of comparisons, I thing it might be confusing to introduce an 
artificial semantic such as 'nil is less than everything'. I think
this is one of those 'ain't broke' situations.


Regards


Dave