Ruby-如何删除哈希数组中的重复项?

时间:2018-06-21 11:44:15

标签: arrays ruby

我在哈希数组中有一个哈希数组。我想根据内部数组的值删除重复项。

{{myservice.mydata}}

您可以在上方看到短语topics = [{"defense"=> [{:id=>30, :source=>"Hacker News", :title=> "China-based campaign breached satellite, defense companies: Symantec", :link=> "https://www.reuters.com/article/us-china-usa-cyber/china-based-campaign-breached-satellite-defense-companies-symantec-idUSKBN1JF2X0"}]}, {"companies"=> [{:id=>30, :source=>"Hacker News", :title=> "China-based campaign breached satellite, defense companies: Symantec", :link=> "https://www.reuters.com/article/us-china-usa-cyber/china-based-campaign-breached-satellite-defense-companies-symantec-idUSKBN1JF2X0"}]}, {"Symantec"=> [{:id=>30, :source=>"Hacker News", :title=> "China-based campaign breached satellite, defense companies: Symantec", :link=> "https://www.reuters.com/article/us-china-usa-cyber/china-based-campaign-breached-satellite-defense-companies-symantec-idUSKBN1JF2X0"}]}] topics.uniq { |phrase, post| post } puts topics defensecompanies包含相同的数组。我如何只保留包含相同数组之一的第一个哈希?

预期输出:

Symantec

注意:在上面的示例中,“短语”的每个内部数组仅包含一个哈希,但是在应用程序中,它可能包含多个帖子。

3 个答案:

答案 0 :(得分:3)

flag=0会将每个唯一值的哈希值减少到一个(任意选择的)键。

答案 1 :(得分:0)

使用此解决方案,您只会得到数组:

topics.map { |topic| topic.values }.uniq.flatten 

它只返回:

# => [{:id=>30, :source=>"Hacker News", :title=>"China-based campaign breached satellite, defense companies: Symantec", :link=>"https://www.reuters.com/article/us-china-usa-cyber/china-based-campaign-breached-satellite-defense-companies-symantec-idUSKBN1JF2X0"}]

答案 2 :(得分:0)

topics = [
  { "defense"   => [{ id: 30, source: "Hacker", title: "China", link: "F2X0"}] },
  { "companies" => [{ id: 30, source: "Hacker", title: "China", link: "F2X0"}] },
  { "Symantec"  => [{ id: 30, source: "Hacker", title: "China", link: "F2X0"}] }
]

topics.uniq { |h| h.values }
  #=> [{"defense"=>[{:id=>30, :source=>"Hacker", :title=>"China", :link=>"F2X0"}]}]

有关uniq使用块的情况,请参见Array#uniq。注意句子“ {self被依次遍历,并且第一次出现被保留。”