On Tue, Jan 5, 2010 at 9:56 PM, Ruby Newbee <rubynewbee / gmail.com> wrote:
> irb(main):038:0* x="hello"
> => "hello"
> irb(main):039:0> x.object_id
> => 69352346
> irb(main):040:0> x.hash
> => 267522041
> irb(main):041:0> y="hello".intern
> => :hello
> irb(main):042:0> y.object_id
> => 246184
> irb(main):043:0> y.hash
> => 246184
>
>
> What's the meanings of String.hash method?
> does it have any relation to object_id? Thanks.

Actually all Objects have both a hash and an eql? method.

They're there to support the implementation of the Hash class, and
there's a strict definition of the relationship between those two
methods.

Hash uses the eql? method to determine if two keys are considered the
same.  The Object class makes eql? the same as ==, but some Objects
override this, for example, 1 == 1.0 returns true, but 1.eql?(1.0)
does not.

For some objects eql? might be somewhat expensive, for example
comparing two large arrays or strings which have many initial elements
equal requires scanning until either the end of one of them or until
an unequal element is found.

So the hash method is used to avoid the Hash object needing to compare
everything.  It must return a fixnum. The definition of Object#hash
states that any overriding implementation must ensure that
self.eql?(another) implies self.hash == other.hash

Comparing two fixnums for equality is very fast, so when a Hash object
wants to determine if it contains a particular object as a key, it
compares the hash of that object to the hash of each of its keys.  If
the two hash values aren't == then the key and the object can't be
eql? so the key can be rejected as a match.  The potentially expensive
comparison using eql? is only done when the hash of the object is ==
to the hash of a key in the hash.  There's a bit more to it than that,
the fixnum hash values can also be used to compute where to look for a
key in the hash table, but the basic idea is that the hash value is a
quick test to rule out two objects being eql?


HTH

-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale