Skip to content

Instantly share code, notes, and snippets.

@eloff
Created July 12, 2016 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eloff/02e1936ef8a0e26333f0cea3467a7443 to your computer and use it in GitHub Desktop.
Save eloff/02e1936ef8a0e26333f0cea3467a7443 to your computer and use it in GitHub Desktop.
def flatten src_array
flat = []
# It would be more readable to just call flat.concat(flatten(...)) recurisvely
# but that creates and destroys a lot of intermediate arrays, which may be costly
append_all(flat, src_array)
flat
end
def append_all dest_array, src_array
src_array.each do |value|
if value.kind_of?(Array)
append_all(dest_array, value)
else
dest_array << value
end
end
end
# Ordinarily I'd add some tests here, but as I don't even know if I meet the
# requirements for this job, I think I've spent enough time on this.
#
# flatten([1,2,[3,[4,5]],[6,7]])
# => [1, 2, 3, 4, 5, 6, 7]
# flatten([[1,2,[3]],4])
# => [1, 2, 3, 4]
# flatten([[1,2,[3,5,[8,9]]],4])
# => [1, 2, 3, 5, 8, 9, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment