我有两个已序列化的YAML文件。
“PP”来自
ἀγαπάω:
present: ἀγαπάω
future: ἀγαπήσω
aorist: ἠγάπησα
......还有更多......
“lexemes”来自
ἀγαπάω:
pos: V
bdag-headword: ἀγαπάω
strongs: 25
gloss: I love
...many more...
我正在尝试将“gloss”和“strongs”的值添加到“pp”,或者将pp值与来自lexemes的这些新值合并。显然ruby不允许在迭代哈希时插入新值。到目前为止,我有:
pps = Hash.new
pp.each do |p|
lexemes.each do |lex, arr|
if lex.match /^#{p[0]}$/
#match found
puts "p #{p[0]} ... lex #{lex}...#{arr['strongs']}....#{arr['gloss']} .
(pps[p[0]] ||= []) << p
pps[p[0]].push(:strongs => arr['strongs'], :gloss => arr['gloss'])
end
end
end
当转储时产生:
"ἀγαπάω":
- - "ἀγαπάω"
- present: "ἀγαπάω"
future: "ἀγαπήσω"
aorist: "ἠγάπησα"
- :strongs: 25
:gloss: I love
当我真正想要的时候:
ἀγαπάω:
present: ἀγαπάω
future: ἀγαπήσω
aorist: ἠγάπησα
strongs: 25
gloss: I love
知道我应该在哪里/如何管理新数据的插入?
谢谢!
答案 0 :(得分:1)
此构造||= []
是Array
的初始化,只是尽量避免它。要合并两个Hash
es,只需使用#merge
方法:
h1 = { h1: { hh1: 1, hh2: 2}}
# => {:h1=>{:hh1=>1, :hh2=>2}}
h2 = { h1: { hh3: 3, hh4: 4}}
# => {:h1=>{:hh3=>3, :hh4=>4}}
h1[:h1].merge(h2[:h1])
# => {:hh1=>1, :hh2=>2, :hh3=>3, :hh4=>4}