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)
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.