flatten an array of arbitrarily nested arrays of integers into a flat array of integers in ruby

冷暖自知 提交于 2020-01-07 09:59:18

问题


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] 


来源:https://stackoverflow.com/questions/35305639/flatten-an-array-of-arbitrarily-nested-arrays-of-integers-into-a-flat-array-of-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!