Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Object#hash

() -> ::Integer
hash → integer

Returns the integer hash value for self; has the property that if foo.eql?(bar) then foo.hash == bar.hash.

Class Hash uses both hash and eql? to determine whether two objects used as hash keys are to be treated as the same key. A hash value that exceeds the capacity of an Integer is truncated before being used.

Many core classes override method Object#hash; other core classes (e.g., Integer) calculate the hash internally, and do not call the hash method when used as a hash key.

When implementing hash for a user-defined class, best practice is to use Array#hash with the class name and the values that are important in the instance; this takes advantage of that method’s logic for safely and efficiently generating a hash value:

Example
def hash
  [self.class, a, b, c].hash
end

The hash value may differ among invocations or implementations of Ruby. If you need stable hash-like identifiers across Ruby invocations and implementations, use a custom method to generate them.

See also #freeze #inspect #extend #instance_of? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0