Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Programmed using Ruby 2.5.1
- # To try this out, run 'ruby array_flatten_test.rb'
- def flatten_array(array, results = [])
- # Loop through each element of the given array
- array.each do |element|
- if element.class == Array
- # If the element is itself an array, we need to flatten that array further
- flatten_array(element, results)
- else
- # If it is a single element, append to the results so far
- results << element
- end
- end
- # Return the results for either the final result, or to flatten further
- results
- end
- require 'minitest/autorun'
- class TestFlatten < Minitest::Test
- def test_flattened_array_1
- assert_equal [1, 2, 3, 4], flatten_array([1, [2, 3], 4])
- end
- def test_flattened_array_2
- assert_equal [1, 2, 3, 4], flatten_array([[1, [2, 3]], 4])
- end
- def test_flattened_array_3
- assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], flatten_array([1, 2, [3, 4, 5], [6, [7, 8, [9, 10]]]])
- end
- end
Add Comment
Please, Sign In to add comment