a = {"rows" => [{"id" => "231-z", "name" => 'jon', "age"=> 27, "state" => 'AL'},
{"id" => "4121-x", "name" => 'ton', "age"=> 37, "state" => 'VA'}
]
}
b = {"rows" => [{"key" => ["xyz","4121-x"], "value" =>{"sum" => 12312, "realage" => 29}},
{"key" => ["xyz","231-z"], "value" =>{"sum" => 1212, "realage" => 33}}
]
}
在哈希a
中,age
不正确
在哈希b
中,realage
是正确的。同样在散列b
中,id是第一个映射到散列id
的{{1}}的数组中的第二个值。那些是4121-x,231-z对应于散列a
我想更正哈希a
中的年龄,并将其与哈希a
的{{1}}交换
我可以分多步完成,但是可以在一个衬里或非常短的时间内完成吗?所以最后正确的哈希realage
应该看起来像
b
答案 0 :(得分:2)
这看起来合理吗?
a['rows'].each_with_index do |ah, i|
(bh = b['rows'].select {|h| h['key'].last == ah['id'] }.first) &&
a['rows'][i] = ah.update('age' => bh['value']['realage'])
end
p a
{
"rows" => [
[0] {
"id" => "231-z",
"name" => "jon",
"age" => 33,
"state" => "AL"
},
[1] {
"id" => "4121-x",
"name" => "ton",
"age" => 29,
"state" => "VA"
}
]
}
请注意,只有在a
中找到相应的id
时才会更新b
。
此外,行顺序无关紧要,行数也无关紧要,b
a
>