来自两个哈希的红宝石单线

时间:2012-12-01 22:06:48

标签: ruby

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

1 个答案:

答案 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 id非常重要a >

Here is a Working Demo