Skip to content

Instantly share code, notes, and snippets.

@bosunolanrewaju
Last active October 25, 2016 17:30
Show Gist options
  • Save bosunolanrewaju/73f414b2cf74ea2d82c17c9a57ed65df to your computer and use it in GitHub Desktop.
Save bosunolanrewaju/73f414b2cf74ea2d82c17c9a57ed65df to your computer and use it in GitHub Desktop.
@flattened_array = [] #To store the flattened array
def flatten(array)
array.each do |value|
# If value is itself an array, call the function recursively
# Store each value found that is not array in the flattened array
value.instance_of? Array ? flatten value : @flattened_array << value
end
@flattened_array
end
#Usage
#flatten [1, 4, 6, [1, 2], [[5, 23], [44, 34, [23, 1]]]]
# => [1, 4, 6, 1, 2, 5, 23, 44, 34, 23, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment