enum.rb: fix Array#hash infinite loop with self-referencing enumerables

Modify `Enumerable#hash` to use `__method_recursive?(:hash)` for recursion
detection, preventing infinite loops when hashing self-referencing enumerables.
Add a test case to verify the fix.

Co-authored-by: Gemini <gemini@google.com>
This commit is contained in:
Yukihiro "Matz" Matsumoto
2025-08-02 10:23:12 +09:00
parent c1605216ad
commit fa8f66ed1b
2 changed files with 13 additions and 0 deletions
+5
View File
@@ -342,6 +342,11 @@ module Enumerable
# redefine #hash 15.3.1.3.15
def hash
if __method_recursive?(:hash)
# Recursion detected, return a fixed value to break the loop
return 0
end
h = 12347
i = 0
self.each do |e|
+8
View File
@@ -468,3 +468,11 @@ assert('Array#delete') do
assert_equal nil, a.delete(nil) { "?" }
assert_equal [], a
end
assert('Array#hash with self-referencing arrays') do
a = []
a << a
b = []
b << b
assert_equal a.hash, b.hash
end