Created
January 7, 2018 21:37
-
-
Save wongjustin99/5de8ff1d79dd9307569847d4f1ac429b to your computer and use it in GitHub Desktop.
Flatten array in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RecursiveFlattenMethod | |
attr_reader :result | |
def flatten_nested_arrays(arr, result=[]) | |
arr.each do |element| | |
if element.class != Array | |
result << element | |
else | |
flatten_nested_arrays(element, result) | |
end | |
end | |
result | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest' | |
require 'minitest/autorun' | |
require './flatten' | |
class FlattenTest < Minitest::Test | |
def test_flatten_arrays | |
bumpy_array = [1, [2, 3, [4, 5]]] | |
expected_result = [1, 2, 3, 4, 5] | |
assert_equal expected_result, RecursiveFlattenMethod.new.flatten_nested_arrays(bumpy_array) | |
end | |
def test_flatten_arrays_different_datatypes | |
bumpy_array = [1, ["2", "3", [4, 5]]] | |
expected_result = [1, "2", "3", 4, 5] | |
assert_equal expected_result, RecursiveFlattenMethod.new.flatten_nested_arrays(bumpy_array) | |
end | |
def test_flatten_arrays_with_array_at_beginning | |
bumpy_array = [[1,6], [2, 3, [4, 5]]] | |
expected_result = [1, 6, 2, 3, 4, 5] | |
assert_equal expected_result, RecursiveFlattenMethod.new.flatten_nested_arrays(bumpy_array) | |
end | |
def test_flatten_arrays_no_nested | |
bumpy_array = [1,6,2,3,4,5] | |
expected_result = [1, 6, 2, 3, 4, 5] | |
assert_equal expected_result, RecursiveFlattenMethod.new.flatten_nested_arrays(bumpy_array) | |
end | |
def test_flatten_arrays_multi_unnecessary_nested | |
bumpy_array = [[[[[1,2,3,4,5]]]]] | |
expected_result = [1, 2, 3, 4, 5] | |
assert_equal expected_result, RecursiveFlattenMethod.new.flatten_nested_arrays(bumpy_array) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment