Reputation: 57
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
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
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
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) }
main_array.any? { |item| item.is_a?(Array) }
if you want to check if main_array
contains any arrays.
Upvotes: 2