7

给定一个包含其他嵌套数组的数组,我想创建一个仅包含第一个数组中的元素的数组。例如 [["1", "2"], "3", [["4"]]] 应该计算为 ["1", "2", "3", "4"]。

我设法制作了一种有效的方法:

@@unwrapped_array = []  
def unwrap_nested_array(array)  
  if array.respond_to?('each')  
    array.each { |elem| unwrap_nested_array(elem) }  
  else  
    @@unwrapped_array.push array  
  end  
end

但我无法弄清楚如何消除 @@unwrapped_array 变量。

4

1 回答 1

11
[["1", "2"], "3", [["4"]]].flatten
# => ["1", "2", "3", "4"]
于 2010-06-30T20:35:49.853 回答