views:

49

answers:

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

+7  A: 
[["1", "2"], "3", [["4"]]].flatten
# => ["1", "2", "3", "4"]
Thom Smith
Thanks! I knew there was an easy answer, just not how easy it was :)
Prisen