按特定条件删除数组元素

时间:2011-02-02 08:31:06

标签: ruby arrays

最好的方法是什么: 我有两个数组:

a=[['a','one'],['b','two'],['c','three'],['d','four']]

b=['two','three']

我想删除a中包含b中元素的嵌套数组,以获取此信息:

[['a','one']['d','four']

感谢。

3 个答案:

答案 0 :(得分:17)

a = [['a','one'],['b','two'],['c','three'],['d','four']]
b = ['two','three']

a.delete_if { |x| b.include?(x.last) }

p a
# => [["a", "one"], ["d", "four"]]

答案 1 :(得分:5)

rassoc救援!

 b.each {|el| a.delete(a.rassoc(el)) }

答案 2 :(得分:2)

a=[['a','one'],['b','two'],['c','three'],['d','four']]
b=['two','three']    
result=a.reject { |e| b.include?(e.first) or b.include?(e.last) }
# result => [["a", "one"], ["d", "four"]]