Hashes in Sets

Discussion in 'Ruby' started by Paul Mucur, Mar 13, 2008.

  1. Paul Mucur

    Paul Mucur Guest

    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.lang.ruby/browse_thread/thread/3ecd14d6e8bbc9cf/88d51de762c3dbd1
    and, more recently, http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/572e8d8b01a7d24e/c5f532d868afab05

    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
    Paul Mucur, Mar 13, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ben Holness

    Hashes of Hashes via subs

    Ben Holness, Oct 5, 2003, in forum: Perl
    Replies:
    8
    Views:
    559
    Ben Holness
    Oct 8, 2003
  2. Steven Arnold

    using hashes as keys in hashes

    Steven Arnold, Nov 23, 2005, in forum: Ruby
    Replies:
    3
    Views:
    159
    Mauricio Fernández
    Nov 23, 2005
  3. kazaam
    Replies:
    12
    Views:
    268
    Matthias Wächter
    Sep 13, 2007
  4. Aaron Patterson

    Hashes, Sets, and eql?

    Aaron Patterson, Nov 24, 2007, in forum: Ruby
    Replies:
    6
    Views:
    101
    Aaron Patterson
    Nov 24, 2007
  5. Tim O'Donovan

    Hash of hashes, of hashes, of arrays of hashes

    Tim O'Donovan, Oct 27, 2005, in forum: Perl Misc
    Replies:
    5
    Views:
    208
Loading...

Share This Page