Skip to content

Instantly share code, notes, and snippets.

@giovannibenussi
Last active September 22, 2016 18:05
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 giovannibenussi/c5ec0ed21f8aa92adf029707277c0004 to your computer and use it in GitHub Desktop.
Save giovannibenussi/c5ec0ed21f8aa92adf029707277c0004 to your computer and use it in GitHub Desktop.
class Array
# Returns the flatten version of the array
# example: [[1,2,[3]],4] -> [1, 2, 3, 4]
def flatten
out = []
self.each do | e |
if e.is_a? Array
out += e.flatten
else
out.push(e)
end
end
return out
end
end
test_arrays = [
[[1,2,[3]],4],
[[1,[2,3,[[4]]]]],
[]
]
for test_array in test_arrays
puts "#{test_array} -> #{test_array.flatten.to_s}"
end
# Output:
# [[1, 2, [3]], 4] -> [1, 2, 3, 4]
# [[1, [2, 3, [[4]]]]] -> [1, 2, 3, 4]
# [] -> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment