Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Hashes in Sets

Reply
Thread Tools

Hashes in Sets

 
 
Paul Mucur
Guest
Posts: n/a
 
      03-13-2008
In Ruby 1.8.6-p111 (the latest version bundled with Mac OS X) and Ruby
1.8.6-p114, the Set class will duplicate any Hash elements it contains:

> require 'set'
> s = Set.new
> s << {}

=> #<Set: {{}}>
> s << {}

=> #<Set: {{}, {}}>
> s << {:a => 1}

=> #<Set: {{:a=>1}, {}, {}}>
> s << {:a => 1}

=> #<Set: {{:a=>1}, {}, {:a=>1}, {}}>

This seems to be due to the fact that the Set class uses a Hash
internally to store its elements as keys and the Hash class itself
does not equate two hashes with the same keys and values:

> {} == {}

=> true
> {}.eql?({})

=> false
> {}.hash == {}.hash

=> false

Defining hash and eql? methods for Hash seems to correct this:

class Hash
# Create a hash based on the keys and values.
def hash
"#{keys.join}#{values.join}".hash
end

# To determine whether two hashes are the same, compare
# their hashes.
def eql?(other)
hash == other.hash
end
end

> {}.eql?({})

=> true
> {:a => 1}.eql?({:a => 1})

=> true
> {:b => 1, :a => 2}.eql?({:a => 2, :b => 1})

=> true
> s = Set.new

=> #<Set: {}>
> s << {}

=> #<Set: {{}}>
> s << {}

=> #<Set: {{}}>

This issue of Hash's eql? method has been brought up before in http://groups.google.com/group/comp....d51de762c3dbd1
and, more recently, http://groups.google.com/group/comp....f532d868afab05

I see that it has been fixed in Ruby 1.9.0 and was wondering if that
change will also be implemented in the 1.8 series?

Thanks in advance,

-- Paul


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
On Hashes - How the hashes printing works? Neela megha shyam Chivukula Ruby 4 05-28-2009 10:56 AM
How to make an array of hashes to a single array with all thevalues of these hashes ? kazaam Ruby 12 09-13-2007 01:30 PM
using hashes as keys in hashes Steven Arnold Ruby 3 11-23-2005 03:25 PM
Hash of hashes, of hashes, of arrays of hashes Tim O'Donovan Perl Misc 5 10-28-2005 05:59 AM
Hashes of Hashes via subs Ben Holness Perl 8 10-08-2003 06:57 AM



Advertisments