嵌套数组的功能展开

Pri*_*sen 7 ruby functional-programming ruby-1.9

给定一个包含其他嵌套数组的数组,我想创建一个只包含第一个数组中元素的数组.例如[["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
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*ith 10

[["1", "2"], "3", [["4"]]].flatten
# => ["1", "2", "3", "4"]
Run Code Online (Sandbox Code Playgroud)