Skip to content

Instantly share code, notes, and snippets.

@zarakay
Created June 28, 2017 10:02
Show Gist options
  • Save zarakay/41f97d763c3e30e4a940b91e2c298e20 to your computer and use it in GitHub Desktop.
Save zarakay/41f97d763c3e30e4a940b91e2c298e20 to your computer and use it in GitHub Desktop.
Interview Question
#!/usr/bin/env ruby
# the custom flatten function
#
# This function will flatten an array.
#
# param 1: the base array to add data to
# param 2: the array to be flattened
def flatten(array, items)
# iterate through each item in the array to be flattened
items.each do |item|
if item.kind_of?(Array)
# if the item is an array, recursively call the
# flatten fuction
array = flatten(array, item)
else
# if the item is not an array, just add it to the base array
array << item
end
end
# return the array
array
end
# the input array
input = [[1,2,[3]],4]
# call the function
output = flatten([], input)
# print out result
puts output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment