Skip to content

Instantly share code, notes, and snippets.

@seanlerner
Created February 7, 2018 01:17
Show Gist options
  • Save seanlerner/c9b57e773f97da6e6e4d66607ec32309 to your computer and use it in GitHub Desktop.
Save seanlerner/c9b57e773f97da6e6e4d66607ec32309 to your computer and use it in GitHub Desktop.
Flatten Array of Integers Without Using Flatten
def flatten_array(input)
input.to_s.gsub(/\[|,|\]/, ' ').split.map(&:to_i)
end
# TEST 1
input = [[1, 2, [3]], 4]
expected = [1, 2, 3, 4]
actual = flatten_array(input)
puts
puts "Input: #{input}"
puts "Expected: #{expected}"
puts "Actual: #{actual}"
puts
if expected == actual
puts 'Test passes'
else
puts 'Test fails'
end
# TEST 2
input = [[[22, [[333]]], 88, [12, 99], [[123]], [5]]]
expected = [22, 333, 88, 12, 99, 123, 5]
actual = flatten_array(input)
puts
puts "Input: #{input}"
puts "Expected: #{expected}"
puts "Actual: #{actual}"
puts
if expected == actual
puts 'Test passes'
else
puts 'Test fails'
end
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment