0

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.

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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 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' }

1 Comment

Ah excellent, thanks a lot! In fact I am sure that it is an array so I went with your first option. I marked Huluk's answer as the correct one because he was faster.
1
> [["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" }]

2 Comments

this will only delete the array ["a", "b"], but not for example ["a", "e"]
I wondered if that was the real question ... update added. Thanks.
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.