Skip to content

Instantly share code, notes, and snippets.

@hoanga
Last active January 25, 2020 04:59
Show Gist options
  • Save hoanga/4955d1da5479dbff12c3eb33b9d26107 to your computer and use it in GitHub Desktop.
Save hoanga/4955d1da5479dbff12c3eb33b9d26107 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# https://gist.github.com/hoanga/4955d1da5479dbff12c3eb33b9d26107
# Returns a flattened version of all elements in the array. Same as Array.flatten
def my_flatten(arr)
result = []
arr.each do |elem|
if elem.kind_of?(Array)
result.concat(my_flatten(elem))
else
result << elem
end
end
return result
end
if __FILE__ == $0
def run_test(input, output)
puts "=========================="
puts "Input: #{input}"
puts "Expected: #{output}"
puts "Got: #{my_flatten(input)}"
puts "Passed? #{my_flatten(input) == output}"
puts ""
end
# Test 1
test_input_array1 = [[1, 2], [3], 4, 5, [7, [8]]]
test_output_array1 = [1,2,3,4,5,7,8]
# Test 2
test_input_array2 = [1, "bb", [[[3]]], [4], :foo, [7, [8]]]
test_output_array2 = [1,"bb",3,4,:foo,7,8]
run_test(test_input_array1, test_output_array1)
run_test(test_input_array2, test_output_array2)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment