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

问题描述 投票:1回答:2

我有一个数组中的字符串列表,如此...

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
2个回答
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

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就像一个Hash只有键,没有值。它们是无序的独特值集合,查找速度非常快。无论playlist_track_names.include?有多大,playlist_track_names都会表现出同样的效果。

© www.soinside.com 2019 - 2024. All rights reserved.