Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 haven't been able to figure out how to eliminate the @@unwrapped_array variable.

like image 919
Prisen Avatar asked Jun 30 '10 20:06

Prisen


1 Answers

[["1", "2"], "3", [["4"]]].flatten
# => ["1", "2", "3", "4"]
like image 104
Thom Smith Avatar answered Sep 22 '22 01:09

Thom Smith