【问题标题】:How do you define element uniqueness by multiple keys/attributes?您如何通过多个键/属性定义元素唯一性?
【发布时间】:2013-06-03 17:03:44
【问题描述】:

我查询了我的数据库,它给了我一个哈希数组,其中哈希中的键是列名。我只想保留根据多个(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

有没有人知道问题出在哪里或有其他解决方法?

谢谢

【问题讨论】:

  • 提供样例输入输出就好了。

标签: ruby arrays attributes unique


【解决方案1】:

我不清楚你要什么。我最好的猜测是给定单关联哈希数组:

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

您希望每个哈希值只有一个哈希;也就是说,删除最后一个 Hash,因为它和第一个都具有 '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"}]

做你想做的。

如果这些猜测都不是您真正想要的,您需要澄清您的要求,最好包括一些示例输入和所需的输出。

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

【讨论】:

  • 谢谢。抱歉含糊其辞,但您的“第二种”解释是我正在寻找的解释,谢谢
  • @Counterfly 没关系;提出明确的问题是一项需要练习的技能。我很高兴我的一个猜测是正确的,我很乐意提供帮助。
【解决方案2】:

如果没有。 of column 是恒定的,即 3 你最好创建一个 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2023-03-08
    相关资源
    最近更新 更多