在特定位置的Ruby哈希中插入条目

给定一个散列,例如,嵌套散列:
hash = {"some_key" => "value","nested" => {"key1" => "val1","key2" => "val2"}}

和String格式的键的路径:

path = "nested.key2"

如何在key2条目之前添加新的键值对?
所以,预期的输出应该是这样的:

hash = {"some_key" => "value","new_key" => "new_value"},"key2" => "val2"}}

EDITED

我的目标是在某些键之前添加一种标签,以便将哈希转储为Yaml文本,并对文本进行后处理,以用Yaml注释替换添加的键/值. AFAIK,没有其他方法可以通过编程方式在YAML中的特定键之前添加注释.

解决方法

使用Hash的数组表示最简单:
subhash   = hash['nested'].to_a
insert_at = subhash.index(subhash.assoc('key2'))
hash['nested'] = Hash[subhash.insert(insert_at,['new_key','new_value'])]

它可以包装成一个函数

class Hash
  def insert_before(key,kvpair)
    arr = to_a
    pos = arr.index(arr.assoc(key))
    if pos
      arr.insert(pos,kvpair)
    else
      arr << kvpair
    end
    replace Hash[arr]
  end
end

hash['nested'].insert_before('key2','new_value'])

p hash # {"some_key"=>"value","nested"=>{"key1"=>"val1","new_key"=>"new_value","key2"=>"val2"}}

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...