给定一个散列,例如,嵌套散列:
- 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"}}