Skip to content

Instantly share code, notes, and snippets.

@umarsheikh
Created October 2, 2017 08:23
Show Gist options
  • Save umarsheikh/254f420bda9744648f05969cb5becc80 to your computer and use it in GitHub Desktop.
Save umarsheikh/254f420bda9744648f05969cb5becc80 to your computer and use it in GitHub Desktop.
Code that flattens arbitrary nested array in ruby
# method: flatten_array
# arguments: an unflattened array, and output array, initially set to [].
# output: a flattened array, so that arbitrary nesting of arrays is removed.
# the method employs tail recursion. It loops over each element of the array.
# if the current element is not an array, it adds it to the array it is building for output.
# but if the current element is an array, then it will call itself recursively so that the next call can iterate over this array element and add items from it recursively.
def flatten_array(array, start=[])
array.each do |elem|
if elem.is_a? Array
flatten_array(elem, start)
else
start << elem
end
end
start
end
#a = [[6, 4, 5], [[1], [2, [7]], [8, 6]], 9, 10, "", ["", nil, false]]
#b = flatten_array(a, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment