ruby 过滤以从数组中排除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32436091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter to exclude elements from array
提问by Rich_F
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?
这不起作用。有没有更好的方法来提供这种过滤器?
回答by The F
Ruby lets you use public instance methods on two arrays to get their intersecting or exclusive elements:
Ruby 允许您在两个数组上使用公共实例方法来获取它们的相交或独占元素:
a1 = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
a2 = ['charlie', 'echo']
puts a1 - a2
=> ['alpha', 'bravo', 'delta']
puts a1 & a2
=> ['charlie', 'echo']
For more information check rubydoc Array. It's likely that you'll find exactly what you need there.
有关更多信息,请查看rubydoc Array。您很可能会在那里找到您需要的东西。
回答by tompave
Your code works for me.
As for "better way", you could use Array#reject:
你的代码对我有用。至于“更好的方法”,您可以使用Array#reject:
total = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
hide = ['charlie', 'echo']
pick = total.reject do |i|
hide.include?(i)
end
puts pick
Not only it is more idiomatic, but Ruby's for i in collectionloops are implemented in terms of collection.each { |i| }. A method with a block is almost always a better alternative.
它不仅更惯用,而且 Ruby 的for i in collection循环是根据collection.each { |i| }. 带有块的方法几乎总是更好的选择。
回答by M-Dahab
How about .select/reject? Or the mutating version .select!/reject!?
.select/reject怎么样?还是变异版本.select!/ reject!?
Here are the docs.
这是文档。
Usage:
用法:
[0, 1, 2, 3].select { |x| x > 1 }
# output: [2, 3]
Or in your case:
或者在你的情况下:
excluded = [0, 1]
[0, 1, 2, 3].reject { |x| excluded.include?(x) }
# output: [2, 3]

