Skip to content

Instantly share code, notes, and snippets.

@wongjustin99
Created January 7, 2018 21:37
Show Gist options
  • Save wongjustin99/5de8ff1d79dd9307569847d4f1ac429b to your computer and use it in GitHub Desktop.
Save wongjustin99/5de8ff1d79dd9307569847d4f1ac429b to your computer and use it in GitHub Desktop.
Flatten array in Ruby
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
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