Created
July 6, 2018 18:12
-
-
Save mthomps/6166f94bd5bece84bda76c1bdb08e05c to your computer and use it in GitHub Desktop.
ruby flatten
This file contains hidden or 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
| def flatten(array) | |
| result = [] | |
| array.each do |item| | |
| if item.is_a? Integer | |
| result << item | |
| else | |
| result.concat(flatten(item)) | |
| end | |
| end | |
| return result | |
| end | |
| puts flatten([[]]) == [] | |
| puts flatten([1]) == [1] | |
| puts flatten([1,2,3]) == [1,2,3] | |
| puts flatten([[[1]],[2,3,[4, [], 5]]]) == [1,2,3,4,5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment