hash_list = {
"a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
"b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
"c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
"d"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false", "id"=>"5"}
}
我期待结果如下,
{
"c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
"d"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false", "id"=>"5"}
}
如何获得上述结果?如果我做
hash_list.invert.invert
然后,我得到了
{
"b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
"c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
"d"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false", "id"=>"5"}
}
在上面的结果中,实际上不需要"b"
。我需要用id维护这个值。
答案 0 :(得分:3)
我将散列g
定义为由散列h
支配当且仅当g[k] == h[k]
用于g
中的所有键时(即, k
中的所有g.keys
。此外,如果存在另一个键值对k=>h
,那么我在hash_list
中将键值对kk=>hh
定义为支配,以便散列{{1}由哈希h
支配。
我假设要返回的哈希只包含来自hh
的非支配键值对。有了这个定义:
hash_list
已被删除,因为它由a
(和b
)和d
已被删除,因为它由b
支配。<强>代码强>
d
示例强>
def remove_dominated_values(hash)
hl = hash.dup
keys = hl.keys
key = keys.shift
while keys.any?
h = hl[key]
hkeys, hvalues = hl[key].keys, hl[key].values
hl.delete(key) if keys.any? { |k| hvalues == hl[k].values_at(*hkeys) }
key = keys.shift
end
hl
end