Skip to content

Instantly share code, notes, and snippets.

@endemic
Last active May 20, 2016 14:24
Show Gist options
  • Save endemic/1d280ad91399b1a17901ed9baa8ccbde to your computer and use it in GitHub Desktop.
Save endemic/1d280ad91399b1a17901ed9baa8ccbde to your computer and use it in GitHub Desktop.
Example "Array#flatten" implementation
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