Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Data#hash

hash → integer

Redefines Object#hash (used to distinguish objects as Hash keys) so that data objects of the same class with same content would have the same hash value, and represented the same Hash key.

Example
Measure = Data.define(:amount, :unit)

Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false

# Structurally similar data class, but shouldn't be considered
# the same hash key
Measurement = Data.define(:amount, :unit)

Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
See also #eql? #inspect #deconstruct_keys #members also in 4.1 · 4.0 · 3.4 · 3.2