Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Hash#compare_by_identity
hash.compare_by_identity → self
hash.c
View on GitHub ↗
VALUE
rb_hash_compare_by_id(VALUE hash)
{
VALUE tmp;
st_table *identtable;
if (rb_hash_compare_by_id_p(hash)) return hash;
rb_hash_modify_check(hash);
if (hash_iterating_p(hash)) {
rb_raise(rb_eRuntimeError, "compare_by_identity during iteration");
}
if (RHASH_TABLE_EMPTY_P(hash)) {
// Fast path: There's nothing to rehash, so we don't need a `tmp` table.
// We're most likely an AR table, so this will need an allocation.
ar_force_convert_table(hash, __FILE__, __LINE__);
HASH_ASSERT(RHASH_ST_TABLE_P(hash));
RHASH_ST_TABLE(hash)->type = &identhash;
}
else {
// Slow path: Need to rehash the members of `self` into a new
// `tmp` table using the new `identhash` compare/hash functions.
tmp = hash_alloc(0);
hash_st_table_init(tmp, &identhash, RHASH_SIZE(hash));
identtable = RHASH_ST_TABLE(tmp);
rb_hash_foreach(hash, rb_hash_rehash_i, (VALUE)tmp);
rb_hash_free(hash);
// We know for sure `identtable` is an st table,
// so we can skip `ar_force_convert_table` here.
RHASH_ST_TABLE_SET(hash, identtable);
RHASH_ST_CLEAR(tmp);
}
return hash;
}
Sets self to consider only identity in comparing keys; two keys are considered the same only if they are the same object; returns self.
By default, these two object are considered to be the same key, so s1 will overwrite s0:
Example
s0 = 'x' s1 = 'x' h = {} h.compare_by_identity? # => false h[s0] = 0 h[s1] = 1 h # => {"x"=>1}
After calling #compare_by_identity, the keys are considered to be different, and therefore do not overwrite each other:
Example
h = {} h.compare_by_identity # => {} h.compare_by_identity? # => true h[s0] = 0 h[s1] = 1 h # => {"x"=>0, "x"=>1}