给定一个散列,例如,嵌套散列:
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"}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。