Created
June 16, 2016 07:40
-
-
Save alip/8a8d456b99f709651c191f4a22b8ff3f to your computer and use it in GitHub Desktop.
Flatten array without Array#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
| #!/usr/bin/env ruby | |
| # coding: utf-8 | |
| def flatten(array) | |
| Array.new.tap do |flat_array| | |
| array.each do |item| | |
| case item | |
| when Numeric | |
| flat_array << item | |
| when Enumerable | |
| flat_array.concat(flatten(item)) | |
| else | |
| fail "Unexpected item #{item.class}, must be an Integer or an Enumerable" | |
| end | |
| end | |
| end | |
| end | |
| x = [1,2,3,[4,5]] | |
| y = [1,2,3,[4,5], [6, [7,8]]] | |
| z = [1,2,3,[4,5], [5, [7,8], [[[8, 9, [7]]]]]] | |
| puts flatten(x).join(',') | |
| puts flatten(y).join(',') | |
| puts flatten(z).join(',') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment