代码之家  ›  专栏  ›  技术社区  ›  Shpigford

如果项与字符串数组匹配,则从Ruby哈希数组中删除项

  •  1
  • Shpigford  · 技术社区  · 6 年前

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

    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

    我该怎么做?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Joseph Cho    6 年前

    它看起来像你的 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
  •  0
  •   Schwern    6 年前

    你可以用 Array#delete_if 删除与块匹配的任何条目。在街区使用 Array#include?

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

    请注意,因为 playlist_track_names.include? 必须搜索 playlist_track_names 一个接一个的速度会变慢 播放列表\曲目\名称 Set

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

    收集 快速查找的值。 播放列表\u曲目_姓名。包括? 播放列表\曲目\名称 得到。