rkm
rkm

Reputation: 57

How to check in Ruby if an array contains other arrays?

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.

Upvotes: 1

Views: 115

Answers (4)

Arup Rakshit
Arup Rakshit

Reputation: 118261

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.

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110665

main_array != main_array.flatten

Upvotes: 1

Ajedi32
Ajedi32

Reputation: 48328

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).

Upvotes: 2

Henrik Andersson
Henrik Andersson

Reputation: 47172

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.

Upvotes: 2

Related Questions