From 3a8d60f50388016a677f250eb4d7c8bbe9d75d7d Mon Sep 17 00:00:00 2001 From: Chris Seaton Date: Sat, 30 Apr 2022 11:57:51 +0100 Subject: Document best-practices for writing hash methods (#5805) * Discussion is as per https://bugs.ruby-lang.org/issues/18611. Co-authored-by: Sam Bostock --- hash.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/hash.c b/hash.c index 1f2bca12b3..797fe6fbfe 100644 --- a/hash.c +++ b/hash.c @@ -303,6 +303,19 @@ objid_hash(VALUE obj) * * Certain core classes such as Integer use built-in hash calculations and * do not call the #hash method when used as a hash key. + * + * When implementing your own #hash based on multiple values, the best + * practice is to combine the class and any values using the hash code of an + * array: + * + * For example: + * + * def hash + * [self.class, a, b, c].hash + * end + * + * The reason for this is that the Array#hash method already has logic for + * safely and efficiently combining multiple hash values. *-- * \private *++ -- cgit v1.2.1