开发者

delete array elements by certain criteria

开发者 https://www.devze.com 2023-02-07 21:25 出处:网络
What\'s the best and way to do this:开发者_如何转开发 I have two arrays: a=[[\'a\',\'one\'],[\'b\',\'two\'],[\'c\',\'three\'],[\'d\',\'four\']]

What's the best and way to do this:开发者_如何转开发 I have two arrays:

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

and b=['two','three']

I want to delete nested arrays inside a that include elements in b,to get this:

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

Thanks.


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"]]


rassoc to the rescue!

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


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"]]
0

精彩评论

暂无评论...
验证码 换一张
取 消