过滤以从数组中排除元素 [英] Filter to exclude elements from array
本文介绍了过滤以从数组中排除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试过滤数组中的某些条目.无法保证它们在主阵列中,因此我正在通过迭代进行测试.
Trying to filter some entries from an array. It's not guaranteed they are in the master array, so I'm testing through an iteration.
total = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
hide = ['charlie', 'echo']
pick = []
for i in total
if !hide.include?(i)
puts i
pick.push(i)
end
end
puts pick
这不起作用.有没有更好的方法来提供这种过滤器?
This isn't working. Is there a better way of providing this kind of filter?
推荐答案
Ruby使您可以在两个数组上使用公共实例方法来获取它们的相交或互斥元素:
Ruby lets you use public instance methods on two arrays to get their intersecting or exclusive elements:
a1 = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
a2 = ['charlie', 'echo']
puts a1 - a2
=> ['alpha', 'bravo', 'delta']
puts a1 & a2
=> ['charlie', 'echo']
有关更多信息,请检查 rubydoc阵列.您很可能会在那里找到所需的东西.
For more information check rubydoc Array. It's likely that you'll find exactly what you need there.
这篇关于过滤以从数组中排除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文