Created
November 18, 2016 22:54
-
-
Save phgrey/43a2267578f3403b3217814d93aa5eb7 to your computer and use it in GitHub Desktop.
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
| # Simple and straight variant - only using if the task will never | |
| # be extended (almost write-only-code) | |
| def flat_me_rube(what) | |
| if what.is_a?(Array) | |
| what.map {|o| flat_me_rube o } # convert all non-array element of array to array too | |
| .reduce &:concat # and then concat them all together | |
| else | |
| [what] # converting itself | |
| end | |
| end | |
| puts flat_me_rube([1, 2, [3], [4, 11], 5, nil]).inspect | |
| # The same function, but split into modules and included to native classes if | |
| # needed, mean logic will be more difficult later | |
| module Flattener | |
| module Element | |
| def flat_me_tender | |
| [self] | |
| end | |
| end | |
| module Array | |
| def flat_me_tender | |
| map(&:flat_me_tender).reduce(&:concat) | |
| end | |
| end | |
| end | |
| #The Int class should be set here if the ONLY int values should be converted | |
| Object.include Flattener::Element | |
| Array.include Flattener::Array | |
| puts [1, 2, [3], [4, 11], 5, nil].flat_me_tender.inspect | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment