[{:id=>30, :source=>"Hacker News", -6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:35 24 4
gpt4 key购买 nike

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

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

您可以在上面看到短语defensecompaniesSymantec 每个都包含相同的数组。我怎样才能只保留包含一个相同数组的第一个散列?

预期输出:

{"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"}]}

注意:在上面的例子中,每个“短语”的内部数组只包含一个散列,但在应用程序中它可以包含多个帖子。

最佳答案

topics.invert.invert 会将每个唯一值的散列简化为单个(任意选择的)键。

关于arrays - Ruby - 如何删除哈希数组中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50967781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com