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]