Last active
May 20, 2016 14:24
-
-
Save endemic/1d280ad91399b1a17901ed9baa8ccbde to your computer and use it in GitHub Desktop.
Example "Array#flatten" implementation
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
def flatten(arg, results = []) | |
if arg.is_a?(Array) | |
arg.each do |val| | |
flatten(val, results) | |
end | |
else | |
results.push(arg) | |
end | |
return results | |
end | |
def assert(condition, message) | |
raise message unless condition | |
end | |
assert(flatten([[1,2,[3]],4]) == [1, 2, 3, 4], 'arrays not equal') | |
assert(flatten([[1,2],[3, 4], 5, 6]) == [1, 2, 3, 4, 5, 6], 'arrays not equal') | |
assert(flatten([1, [2, [3, [4, [5, [6]]]]]]) == [1, 2, 3, 4, 5, 6], 'arrays not equal') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment