如果数组中的值与给定字符串匹配,我将尝试从数组中删除元素。
我有一个包含标签数组的数组。我正在比较标签的名称,看看它们是否与用户希望从搜索中排除的内容相匹配。如果是这样,我想从主数组中删除该元素,或者可能添加不匹配的元素。
这是我目前所拥有的:
results = Array.new
test = 0
no_tags.each do |no_tag| #an array of tags whose resources are not to be included
resources.each do |r|
add_to_array = false
r.tags.each do |t|
if t.name.eql? no_tag
test += 1
add_to_array = false
else
add_to_array = true
end
end
if add_to_array
results << r
end
end
end
test 变量只是一个用于调试匹配出现次数的变量,恰好是 763 个资源中的 141 个。然而,当我在这个 block 运行后执行 results.count 时,我只得到 732,而我应该得到 622。
为了澄清,如果标签数组包含匹配项,我需要删除资源数组的元素,或者如果未找到匹配项,另一个选项是将资源数组元素包含到新数组中。
这将作为 JSON 返回给浏览器,我需要排除其标签与 no_tags 数组的值匹配的资源。
最佳答案
您可以测试 names 和 no_tags 的交集。它应该是空的。
results = resources.select do |r|
(r.tags.map(&:name) & no_tags).empty?
end
关于ruby - 当字符串匹配标签时删除数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9690247/