Created
February 13, 2020 10:26
-
-
Save Maxcutex/506d116bd0d10b7d7c0073a1053520eb to your computer and use it in GitHub Desktop.
Ruby script to flatten a list of list.
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 "test/unit/assertions" | |
include Test::Unit::Assertions | |
def recursive_flatten(array, results = []) | |
array.each do |element| | |
if element.class == Array | |
recursive_flatten(element, results) | |
else | |
results << element | |
end | |
end | |
results | |
end | |
# TEST | |
assert_equal([1, 2, 3, 4, 5, 6, 7, 8, 9], recursive_flatten([1,2,3, [4,5], 6, [7,8], 9])) | |
assert_not_equal([1, 2, 3, 4, 6], recursive_flatten([1, 2, [3, [4, 5]], 6])) | |
assert_equal([1, 2, 3, 4], recursive_flatten([[1,2,[3]],4])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment