如果item匹配字符串数组,则从Ruby哈希数组中删除项目
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果item匹配字符串数组,则从Ruby哈希数组中删除项目相关的知识,希望对你有一定的参考价值。
我有一个数组中的字符串列表,如此...
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
数组中的任何名称。
我该怎么办?
答案
看起来你的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
另一答案
您可以使用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
都会表现出同样的效果。
以上是关于如果item匹配字符串数组,则从Ruby哈希数组中删除项目的主要内容,如果未能解决你的问题,请参考以下文章
TS / JS-如果对象的属性与数组中的另一个属性相匹配,则从对象数组中获取“值”