coderz
coderz

Reputation: 4999

Ruby, hash and object_id

I use Ruby 2.2.2.

irb(main):002:0> str = "abc"
=> "abc"
irb(main):003:0> str2 = "abc"
=> "abc"
irb(main):004:0> str.hash
=> -340360941
irb(main):005:0> str2.hash
=> -340360941
irb(main):006:0> str.object_id
=> 3702564
irb(main):007:0> str2.object_id
=> 24864312
irb(main):009:0> str == str2
=> true
irb(main):010:0> str.eql? str2
=> true

Why str and str2 have same hash, but different object_id? According to doc hash and object_id, no two active objects will share an id, so str and str2 have different object_id, but how to understand their hash are same?

Could anybody tell something about this? My guess is that "abc" only occupy one memory space, and both str and str2 referenced to the same memory space.

If someone could explain it in how memory is allocated, that will be great.

Upvotes: 0

Views: 1102

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84182

object_id (and the corresponding equal? method) are concerned with object identity: are these 2 objects the exact same object? subclasses don't (or at least shouldn't) override this.

On the other hand == and eql? are more about object values: do these two objects represent the same value? This is of course dependant on the class, so it is quite possible to have two different objects (their object_id is different) that are equal in this respect. The hash method's contract that equal objects must have equal hash value is for eql?, so it's normal that two objects can have different object_id but have the same hash.

In your example your 2 strings are different objects that, at that particular point in time, happen to contain the same sequence of bytes

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

My guess is that "abc" only occupy one memory space, and both str and str2 referenced to the same memory space.

Whether that was true, their object_id were the same. The string is created twice and str instance has nothing to do with str2 instance. Otherwise, str[1] = "A" led to both variables change, transforming str2‘s value to aAc.

When objects‘ values are equal, their hashes are to be equal for quick lookup/search etc.

E.g. John Smith from Ohio and John Smith from Oklahoma share the same name, what makes their hash equal, but since they are definitely not the same person, their object_id differ.

Upvotes: 2

Related Questions