开发者

Functional unwrapping of nested array

Given an array containing other nested arrays, I want to create an array containing only the elements from the first array. For example [["1", "2"], "3", [["4"]]] should evaluate to ["1", "2", "3", "4"].

I've managed to make a method that works:

@@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

but I have开发者_StackOverflown't been able to figure out how to eliminate the @@unwrapped_array variable.


[["1", "2"], "3", [["4"]]].flatten
# => ["1", "2", "3", "4"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜