Muhammad Umer
Muhammad Umer

Reputation: 18097

How to check if any element in array is also an array

I want to check if array has any elements that are instances of Array. I could make a recursive function and that iterates and finds all elements that are Array. Is there a shorter way to do this?

Get all elements that are of x type and manipulate them (i.e. modify or delete them)

Upvotes: 0

Views: 191

Answers (2)

Wand Maker
Wand Maker

Reputation: 18762

Here is one possible solution,
You can use Ruby blocks to act on sub-arrays & nested sub-arrays recursively.

arr = [1, [2,3], [4,[5,6]]]

def act_on_array(arr, block) 
    arr.each do |i|  
        if i.is_a?(Array) then
            block.yield(i)
            act_on_array(i, block)
        end
    end 
end

act_on_array(arr, lambda {|x| puts "I should act on #{x} as it is an array" })

Output of program

I should act on [2, 3] as it is an array
I should act on [4, [5, 6]] as it is an array
I should act on [5, 6] as it is an array

Upvotes: 0

sawa
sawa

Reputation: 168101

It can be done this way:

array.any?{|e| e.is_a?(Array)}

Upvotes: 4

Related Questions