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.
[["1", "2"], "3", [["4"]]].flatten
# => ["1", "2", "3", "4"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With