hashery icon indicating copy to clipboard operation
hashery copied to clipboard

Dictionary cannot contain 'nil' key

Open alexnixon opened this issue 13 years ago • 3 comments

The following does not work:

require 'rubygems' require 'hashery'

d = Dictionary.new d[0] = 1 d[nil] = 2 d.order_by_key

=>ArgumentError: comparison of Fixnum with nil failed

alexnixon avatar Apr 27 '11 12:04 alexnixon

Yea. This is a general issue with NilClass. For example:

ruby-1.8.7-p302 > [1, nil].sort
ArgumentError: comparison of Fixnum with nil failed
      from (irb):1:in `sort'
      from (irb):1

So nil is not sortable in general.

However you can get around this by setting #order_by yourself.

d.order_by{ |k,v| k.nil? ? "" : k }

Where "" is the result to compare to when the key is nil. The only reason we can't do this by default is b/c of "" --what it is depends on the application's needs.

trans avatar Apr 27 '11 18:04 trans

Hmm to me it still seems unintuitive for a container to be able to enter an inconsistent state where even 'inspect' fails. Perhaps that's just my statically-typed background showing through, though.

On Wed, Apr 27, 2011 at 7:22 PM, trans < [email protected]>wrote:

Yea. This is a general issue with NilClass. For example:

ruby-1.8.7-p302 > [1, nil].sort ArgumentError: comparison of Fixnum with nil failed from (irb):1:in `sort' from (irb):1

So nil is not sortable in general.

However you can get around this by setting #order_by yourself.

d.order_by{ |k,v| k.nil? ? "" : k }

Where "" is the result to compare to when the key is nil. The only reason we can't do this by default is b/c of "" --what it is depends on the applications needs.

Reply to this email directly or view it on GitHub: https://github.com/rubyworks/hashery/issues/7#comment_1065891

alexnixon avatar Apr 28 '11 11:04 alexnixon

That's a good point about #inspect. I'm just not sure how to get around it. Consider also that any object can be used as a key, but if #<=> is not defined for that object it will error too.

I'm open to suggestions.

trans avatar Apr 28 '11 12:04 trans