Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dictionary cannot contain 'nil' key #7

Open
alexnixon opened this issue Apr 27, 2011 · 3 comments
Open

Dictionary cannot contain 'nil' key #7

alexnixon opened this issue Apr 27, 2011 · 3 comments

Comments

@alexnixon
Copy link

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

@trans
Copy link
Member

trans commented Apr 27, 2011

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.

@alexnixon
Copy link
Author

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:
#7 (comment)

@trans
Copy link
Member

trans commented Apr 28, 2011

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants