Guest User

Untitled

a guest
Apr 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. # Programmed using Ruby 2.5.1
  2. # To try this out, run 'ruby array_flatten_test.rb'
  3.  
  4. def flatten_array(array, results = [])
  5. # Loop through each element of the given array
  6. array.each do |element|
  7. if element.class == Array
  8. # If the element is itself an array, we need to flatten that array further
  9. flatten_array(element, results)
  10. else
  11. # If it is a single element, append to the results so far
  12. results << element
  13. end
  14. end
  15. # Return the results for either the final result, or to flatten further
  16. results
  17. end
  18.  
  19. require 'minitest/autorun'
  20.  
  21. class TestFlatten < Minitest::Test
  22. def test_flattened_array_1
  23. assert_equal [1, 2, 3, 4], flatten_array([1, [2, 3], 4])
  24. end
  25.  
  26. def test_flattened_array_2
  27. assert_equal [1, 2, 3, 4], flatten_array([[1, [2, 3]], 4])
  28. end
  29.  
  30. def test_flattened_array_3
  31. assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], flatten_array([1, 2, [3, 4, 5], [6, [7, 8, [9, 10]]]])
  32. end
  33. end
Add Comment
Please, Sign In to add comment