开发者

Functional unwrapping of nested array

开发者 https://www.devze.com 2023-01-05 12:14 出处:网络
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\", \"

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

精彩评论

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