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

时间:2018-08-29 21:39:20

标签: arrays ruby hash

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

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 个答案:

答案 0 :(得分:2)

您的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

答案 1 :(得分:0)

您可以使用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就像一个哈希,只有键,没有值。它们是唯一值的无序集合,可以快速查找。无论playlist_track_names.include?变大,集合上的playlist_track_names都将执行相同的操作。