0

I want to count the number of arrays in the nested arrays of an array

array = [[["-", 0, "I"], ["+", 0, "you"]], [["+", 3, "i"]], [["-", 4, "loved"], ["-", 5, "that"], ["+", 5, "it"], ["+", 6, "tasted"], ["+", 7, "like"]]]

This example would have 8 nested arrays inside the arrays in the array array. (not sure if I worded that right)

11
  • 1
    What do you want here? 8? You could use Regular Expression for that. I think it's the simplest way Commented Mar 10, 2016 at 1:05
  • 1
    array.first.count should do? @Desorder - could you explain how you would use RegularExpressions here? Commented Mar 10, 2016 at 1:06
  • 1
    @BroiSatse array.first.count and array.first.size gives 2. Commented Mar 10, 2016 at 1:10
  • 1
    Ah, there are two arrays, hard to spot those brackets. array.flatten(1).count will do. Commented Mar 10, 2016 at 1:11
  • 2
    @Desorder - Regex can be used for strings, how do you want to apply regex pattern to an array? Convert it to string first? Commented Mar 10, 2016 at 1:16

2 Answers 2

6

The easiest/cleanest way is to partially flatten an array by one nesting level:

array.flatten(1).count

Other option is to sum sub-arrays:

array.inject([], :+).count

However the real question you need to ask to yourself is - how did I end up with such a weird construct?

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

Comments

0

The key here is to properly state the question - I assume it to be count the number of arrays inside the nested array, which themselves do not contain another arrays.

def count_inner_arrays(arr)
  sub_arrays = arr.select { |el| el.is_a? Array }
  sub_arrays.empty? ? 1 : sub_arrays.map(&method(:count_inner_arrays)).inject(0, :+)
end  

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.