ruby picture

RCR 344: Implement Hash#hash

Submitted by Eludias (Thu Aug 17 19:57:27 UTC 2006)

Abstract

Make Hash#hash look at contents just like Array#hash

Problem

Array#hash and Hash#hash are inconsistent: Array#hash _does_ look at the contents, while Hash#hash _doesn't_.

For example:

  a = {}
  a[[1,2]] = 10
..now a[[1,2]] gives 10.
  a[{1=>2}] = 11
..now a[{1=>2}] gives nil.

I stumbled upon this while grouping an array of objects based on an aspect (something like Array#sort_by). When I changed the aspect from an Array to an Hash, the grouping stopped working.

Proposal

Let Hash#hash look at the contents to remove inconsistancy.

Analysis

This should only effect code which puts hashes in hashes. Currently, there is not much use for that since the keys cannot be retrieved any more except by the initial key, so it should not effect (many) existing programs.

Implementation

class Hash
    # By default, the hashcode of hash doesn't look at the
    # contents. This makes indexing a hash with a hash impossible.
    def hash
        inject(0) { |h, p| h ^ p[0].hash ^ p[1].hash }
    end
    # When implementing #hash, eql? should be adapted.
    def eql?(other)
        super || other == self
    end
end
ruby picture
Comments Current voting
I voted mildly against it, mostly because I personally think that Hash#hash is not a really good name, if you compare it to other methods like Hash#keys for example.


Strongly opposed 0
Opposed 2
Neutral 0
In favor 1
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .