加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Ruby中通过递归嵌套哈希

发布时间:2020-12-17 03:08:05 所属栏目:百科 来源:网络整理
导读:我一直在尝试在 Ruby中以编程方式创建嵌套的默认哈希,基本上是Ruby的简写: h = Hash.new {|h,k| h[k] = Hash.new} 我想将其扩展到需要的多个级别.我做了以下功能: def nested_hash(level,default={}) return default if level == 0 return Hash.new{ |h,k|
我一直在尝试在 Ruby中以编程方式创建嵌套的默认哈希,基本上是Ruby的简写:

h = Hash.new {|h,k| h[k] = Hash.new}

我想将其扩展到需要的多个级别.我做了以下功能:

def nested_hash(level,default={})
   return default if level == 0
   return Hash.new{ |h,k| h[k] = nested_hash(level - 1,default) }
end

它看起来工作正常,但在创建多个键时遇到以下问题

h = nested_hash(1)
h[0][1] = [1,2,3] # h is {0=>{1=>[1,3]}}
h[2] # should give a new Hash,but returns {1=>[1,3]}
h # {0=>{1=>[1,3]},2=>{1=>[1,3]}}

为什么函数的默认值会更改并成为先前设置的值?

编辑

我找到了一个有效的解决方案:

def nested_hash(level,default={})
    return Hash.new{ |h,k| h[k] = default } if level <= 1
    Hash.new{ |h,default) }
end

没关系,这不会以类似的方式工作:

h = nested_hash(1)
h[0][1] = [1,3]
h[2][0] # nil
h # {0=>{1=>[1,3]}}

我仍然对为什么原始默认值在密钥之间共享感到困惑.

解决方法

只是出于好奇:

hash =
  Hash.new do |h,k|
    h[k] = h.dup.clear.extend(Module.new do
      define_method(:level,->{ h.level - 1 })
    end).tap { |this| raise "                        

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读