How to smooth subarrays in Ruby?

I have the following structure

a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]

and I want to get the following:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]

I tried the following:

a.flatten => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l', 'm', 'n']

a.flatten(1) => ['a', 'b', 'c', 'd', 'e', 'f', ['g', 'h', 'i'], ['l', 'm', 'n']]

The solution I found now is to change the original structure to this format:

b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]

and then call

b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]

but I could only do this because I was able to change the way I created it a. My question remains: how to get the desired result, starting with a?

+4
source share
2 answers
a.each_with_object([]) do |e, memo|
  e == e.flatten ? memo << e : e.each { |e| memo << e }
end
#⇒ [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
+6
source

Another solution:

a.flat_map { |e| e[0].is_a?(Array) ? e : [e] }
#=> [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["l", "m", "n"]]
+4
source

Source: https://habr.com/ru/post/1653886/


All Articles