合并散列数组并进行验证

时间:2014-02-19 13:54:03

标签: ruby arrays hash

如果某些键匹配,我想将一个哈希数组合并到另一个哈希数组。例如,我有这个:

data = [{"a"=>1, "b"=>2, "c"=>3}, {"a"=>1, "b"=>5, "c"=>7}]
new_data = [{"a"=>1, "b"=>2, "z"=>10}]

运行一些方法,如下所示:

merge_with_validation(data, new_data, ["a","b"])

我希望结果如下:

[{"a"=>1, "b"=>2, "c"=>3, "z"=>10}, {"a"=>1, "b"=>5, "c"=>7, "z"=>nil}]

当密钥datanew_data中的值匹配时,结果ab合并。


回复更新

我使用Arup Rakshit的答案进行了一些改动:

def merge_with_validation(data, new_data, keys)
  data.map do |hash|
    if hash.values_at(*keys) ==  new_data.first.values_at(*keys)
      next hash.merge(new_data.shift)
    end
    hash
  end
end

2 个答案:

答案 0 :(得分:1)

我会做

data = [{"a"=>1, "b"=>2, "c"=>3}, {"a"=>1, "b"=>5, "c"=>7}]
new_data = [{"a"=>1, "b"=>2, "z"=>10}]

def merge_with_validation(data, new_data, keys)
    data.map do |hash|
       if hash.values_at(*keys) ==  new_data.first.values_at(*keys)
           next hash.merge(new_data.first)
       end
       hash.merge({"z"=>nil})
    end
end

merge_with_validation(data, new_data, ["a","b"]) 
# => [{"a"=>1, "b"=>2, "c"=>3, "z"=>10}, {"a"=>1, "b"=>5, "c"=>7, "z" => nil}]

答案 1 :(得分:0)

这个怎么样:

请注意,我们不是以编程方式检查缺失的密钥(即“z”),但我们可以这样做

def merge_with_validation(data, new_data, keys)
    data.each_with_object([]).with_index { |(e,arr), i| 
       new_hash = new_data[i] || e
       new_hash["z"] = nil if !new_hash["z"]
       arr << e.merge(new_hash) if keys.all? { |k| e[k] ==  new_hash[k]} 
    }
end

返回:

merge_with_validation(data,new_data, %w(a b))
=> [{"a"=>1, "b"=>2, "c"=>3, "z"=>10}, {"a"=>1, "b"=>5, "c"=>7, "z"=>nil}]

如果你发现错误我会告诉我,我会解决(我为足球而迟到了: - ))