无法定位stack level too deep错误,求助排查哈希扁平化代码问题
Hey there! Let's break down why you're hitting that stack overflow issue and get your hash flattening function working correctly.
The Root Cause
The problem is in your recursive call: you're passing the original hash instead of the nested value that you just confirmed is a Hash. This means every recursive call loops over the same top-level hash forever, leading to infinite recursion and the stack overflow error.
Look at this line in your code:
pathifize(hash,results, combined_key, b)
You should be passing value here, since that's the nested hash you need to process next.
Fixed Code
Here's the corrected version of your function, with that critical fix plus a small tweak to make the return value explicit (since your original code would return the input hash instead of the accumulated results):
require 'active_support' require 'active_support/core_ext' def pathifize(hash, results = {}, current_key='', separator = ".") hash.each do |new_key, value| combined_key = [current_key, new_key].delete_if { |k| k.blank? }.join(separator) if value.is_a?(Hash) # Recurse on the nested value, not the original hash! pathifize(value, results, combined_key, separator) else results[combined_key] = value end end # Return the accumulated flattened results results end
Testing It Out
Let's verify with your example input:
pathifize({a: {b: 1}}) # => {"a.b"=>1}
And a more complex nested hash to confirm it handles deeper levels:
pathifize({x: 2, y: {z: 3, w: {v: 4}, u: 5}}) # => {"x"=>2, "y.z"=>3, "y.w.v"=>4, "y.u"=>5}
Quick Notes
- I renamed the
bparameter toseparatorfor readability—this is optional, but makes the code easier to follow for anyone reading it later. - The explicit
return resultsat the end ensures the function gives back the flattened hash (without this,Hash#eachwould return the original input hash instead). - Your use of
delete_if { |k| k.blank? }works perfectly with ActiveSupport'sblank?to handle the initial emptycurrent_keycorrectly.
内容的提问来源于stack exchange,提问作者Arb

