You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法定位stack level too deep错误,求助排查哈希扁平化代码问题

Fixing the "stack level too deep" Error in Your Pathifize Function

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 b parameter to separator for readability—this is optional, but makes the code easier to follow for anyone reading it later.
  • The explicit return results at the end ensures the function gives back the flattened hash (without this, Hash#each would return the original input hash instead).
  • Your use of delete_if { |k| k.blank? } works perfectly with ActiveSupport's blank? to handle the initial empty current_key correctly.

内容的提问来源于stack exchange,提问作者Arb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:39:36