1

I have a multidimensional array like this:

main_array = [ [["a","b","c"],["d","e"]], [["e","f"],["g","h"]]  ]  

And I would like to check whether main_array contains other arrays.
I've thought that this will work main_array.include?(Array), but i was wrong.

1
  • a.any? { |e| Array === e } also works. Commented May 19, 2014 at 22:40

4 Answers 4

3

To answer your question directly, I will use #grep method

 main_array.grep(Array).empty?

This will ensure that, if your main_array contains at least one element as Array, if returns false.

 main_array.grep(Array).size == main_array.size

This will tell you, if all elements are array or not.

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

2 Comments

Good answer, but should is the logic not reversed in the first example?
@hirolau First one is for to check if any element is an array or not, the last to check all elements are array or not
2

You can use the Enumerable#all? if you want to check that the main array contains all arrays.

main_array.all? { |item| item.is_a?(Array) }

or Enumerable#any?

main_array.any? { |item| item.is_a?(Array) }

if you want to check if main_array contains any arrays.

Comments

2

You can use Enumerable#any?:

main_array.any?{|element| element.is_a? Array}

The code you tried (main_array.include?(Array) didn't work because it's checking if the array main_array includes the class Array, e.g. [Array].include?(Array) #=> true).

Comments

1
main_array != main_array.flatten

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.