【问题标题】:Delete item from Ruby array of hashes if item matches array of strings如果项目与字符串数组匹配,则从 Ruby 哈希数组中删除项目
【发布时间】:2018-08-29 21:39:19
【问题描述】:

我有一个像这样的数组中的字符串列表......

playlist_track_names = ["I Might", "Me & You", "Day 1", "I Got You (feat. Nana Rogues)", "Feels So Good (feat. Anna of the North)", "306", "Location Unknown (feat. Georgia)", "Crying Over You (feat. BEKA)", "Shrink", "I Just Wanna Go Back", "Sometimes", "Forget Me Not"] 

然后我有一个这样的哈希数组......

[
  {"id"=>"1426036284", "type"=>"songs", "attributes"=>{"name"=>"I Might", "albumName"=>"Love Me / Love Me Not" },
  {"id"=>"1426036285", "type"=>"songs", "attributes"=>{"name"=>"Feels So Good (feat. Anna of the North)", "albumName"=>"Love Me / Love Me Not" },
  {"id"=>"1426036286", "type"=>"songs", "attributes"=>{"name"=>"Forget Me Not", "albumName"=>"Love Me / Love Me Not" },
  {"id"=>"1426036287", "type"=>"songs", "attributes"=>{"name"=>"Some Other Name", "albumName"=>"Love Me / Love Me Not" }
]

我想要做的是从哈希数组中删除 attributes['name']playlist_track_names 数组中的任何名称匹配的任何项目。

我该怎么做?

【问题讨论】:

标签: arrays ruby hash


【解决方案1】:

您的hash_list 似乎缺少一些右括号。我在下面添加了它们。尝试在 irb 中运行:

playlist_track_names = ["I Might", "Me & You", "Day 1", "I Got You (feat. Nana Rogues)", "Feels So Good (feat. Anna of the North)", "306", "Location Unknown (feat. Georgia)", "Crying Over You (feat. BEKA)", "Shrink", "I Just Wanna Go Back", "Sometimes", "Forget Me Not"] 

hash_list = [
  {"id"=>"1426036284", "type"=>"songs", "attributes"=>{"name"=>"I Might", "albumName"=>"Love Me / Love Me Not" } },
  {"id"=>"1426036285", "type"=>"songs", "attributes"=>{"name"=>"Feels So Good (feat. Anna of the North)", "albumName"=>"Love Me / Love Me Not" } },
  {"id"=>"1426036286", "type"=>"songs", "attributes"=>{"name"=>"Forget Me Not", "albumName"=>"Love Me / Love Me Not" } },
  {"id"=>"1426036287", "type"=>"songs", "attributes"=>{"name"=>"Some Other Name", "albumName"=>"Love Me / Love Me Not" } }
]

hash_list.delete_if { |i| playlist_track_names.include? i["attributes"]["name"] }
puts hash_list

【讨论】:

    【解决方案2】:

    您可以使用Array#delete_if 删除任何匹配块的条目。在块中使用Array#include? 检查曲目名称是否在列表中。

    tracks.delete_if { |track|
      playlist_track_names.include? track["attributes"]["name"]
    }
    

    请注意,因为playlist_track_names.include? 必须逐个搜索playlist_track_names,所以随着playlist_track_names 变大,这会变慢。您可以使用Set 来避免这种情况。

    require 'set'
    
    playlist_track_names = ["I Might", "Me & You", ...].to_set
    

    Set 就像一个只有键,没有值的哈希。它们是 unorderedunique 值集合,查找起来非常快。无论playlist_track_names 有多大,Set 上的playlist_track_names.include? 都会执行相同的操作。

    【讨论】:

    • 我从来不知道set。感谢您的知识
    猜你喜欢
    • 2012-04-17
    • 2021-11-14
    • 1970-01-01
    • 2021-12-28
    • 2015-08-20
    • 2020-07-18
    • 2019-09-22
    • 2014-12-22
    • 1970-01-01
    相关资源
    最近更新 更多