flatten an array of arbitrarily nested arrays of i

2019-09-22 11:08发布

问题:

how to write a code snippet Ruby that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. Please don't use any built-in flatten functions in either language.

回答1:

Here's one solution without using the built-in flatten method. It involves recursion

def flattify(array)
  array.each_with_object([]) do |element, flattened|
    flattened.push *(element.is_a?(Array) ? flattify(element) : element)
  end
end

I tested this out in irb.

flattify([[1,2,[3],4])
=> [1,2,3,4]


回答2:

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

If, as in you example, arr contains only numbers, you could (as opposed to "should") do this:

eval "[#{arr.to_s.delete('[]')}]"
 => [1, 2, 3, 4]