如何通过多个键/属性定义元素唯一性



我查询了我的数据库,它给了我一个哈希数组,其中哈希中的键是列名。我想只保留哈希值(数组元素),根据多个(3列)是唯一的。我试过了:

array.uniq { |item| item[:col1], item[:col2], item[:col3] }

array = array.inject([{}]) do |res, item|
    if !res.any? { |h| h[:col1] == item[:col1] && 
                       h[:col2] == item[:col2] && 
                       h[:col3] == item[:col3] }
        res << item
    end
end

有没有人有任何想法,什么是错的或另一种方式去做这件事?

谢谢

我不明白你想要什么。我最好的猜测是,给定单关联哈希数组:

array = [{:col1 => 'aaa'}, {:col2 => 'bbb'}, {:col3 => 'aaa'}]

你希望每个哈希值只有一个哈希;也就是说,删除最后一个散列,因为它和第一个散列的值都是'aaa'。如果是,则如下:

array.uniq{|item| item.values.first}
# => [{:col1=>"aaa"}, {:col2=>"bbb"}]

做你想做的。

我想象的另一种可能性是给定一个这样的数组:

array2 = [{:col1 => 'a', :col2 => 'b', :col3 => 'c', :col4 => 'x'},
          {:col1 => 'd', :col2 => 'b', :col3 => 'c', :col4 => 'y'},
          {:col1 => 'a', :col2 => 'b', :col3 => 'c', :col4 => 'z'}]

您希望排除最后一个散列,因为:col1, :col2:col3的值与第一个散列的值相同。如果是,则如下:

array2.uniq{|item| [item[:col1], item[:col2], item[:col3]]}
# => [{:col1=>"a", :col2=>"b", :col3=>"c", :col4=>"x"},
#     {:col1=>"d", :col2=>"b", :col3=>"c", :col4=>"y"}]

做你想做的。

如果这两个猜测都不是你想要的,你需要澄清你想要什么,最好包括一些示例输入和期望的输出。

我还将指出,您很有可能在数据库查询级别完成您想要的操作,这取决于许多未给出的因素。

列是常量,即3,你最好创建一个3级哈希,如下所示你想要存储的任何值都在第三层。

out_hash = Hash.new
array.each do |value|
if value[:col1].nil?
     out_hash[value[:col1]] = Hash.new
     out_hash[value[:col1]][value[:col2]] = Hash.new
     out_hash[value[:col1]][value[:col2]][value[:col3]] = value
else if value[:col1][:col2].nil?
     out_hash[value[:col1]][value[:col2]] = Hash.new
     out_hash[value[:col1]][value[:col2]][value[:col3]] = value
else if value[:col1][:col2][:col3].nil?
      out_hash[value[:col1]][value[:col2]][value[:col3]] = value
end
end

我没有测试上面的代码,它给你一个想法…

最新更新