简体   繁体   中英

How to remove an array from another array in Ruby?

I have a nested array in Ruby:

array = [["a", "b"], ["c", "d"]]

What command can I use to remove the nested array that contains "a" from the array?

Thanks for any help.

array.delete_if{|ary| ary.kind_of?(Array) and ary.include?('a') } array.delete_if{|ary| ary.kind_of?(Array) and ary.include?('a') } Deletes all arrays which include "a"

Do you specifically want to remove ["a", "b"] , knowing that's exactly what it is, or do you want to remove any and all arrays that contain "a" , no matter their remaining values? It's not clear whether you meant 'the nested array that contains "a"' as part of the problem specification, or just a way of indicating which of the elements in your specific example you wanted the answer to target.

For the first one, you can use DigitalRoss's answer.

For the second, you can use Huluk's, but it's overly specific in another way; I would avoid the kind_of? Array kind_of? Array test. If you know the elements are all arrays, then just assume it and move on, relying on exceptions to catch any, well, exceptions:

array.delete_if { |sub| sub.include? 'a' }

If you do need to test, I would use duck-typing instead of an explicit class check:

array.delete_if { |item| item.respond_to? :include? and item.include? 'a' }
> [["a", "b"], ["c", "d"]] - [["a", "b"]]
 => [["c", "d"]] 

If you don't already have a handle on the element other than knowing it contains an "a", you can do:

array - [array.find { |x| x.include? "a" }]

尝试这个:

   array.delete_if { |x| x.include? "a" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM