Skip to content

Instantly share code, notes, and snippets.

@fastzen
Created August 30, 2016 18:23
Show Gist options
  • Save fastzen/39fbe69acbc1e154a68cd78a75929227 to your computer and use it in GitHub Desktop.
Save fastzen/39fbe69acbc1e154a68cd78a75929227 to your computer and use it in GitHub Desktop.
flatten
#!/usr/bin/env ruby
# encoding: utf-8
require "test/unit"
# Flatten an array given any nesting depth
def flatten(array, result = [])
return result unless array.is_a?(Array)
array.each do |element|
if element.is_a?(Array)
flatten(element, result)
else
result << element
end
end
return result
end
class TestFlatten < Test::Unit::TestCase
def test_flatten_no_array
source = 1
target = []
assert_equal( target, flatten( source ) )
end
def test_flatten_no_depth
source = [1,2,3,4]
target = [1,2,3,4]
assert_equal( target, flatten( source ) )
end
def test_flatten
source = [[1,2,[3]],4]
target = [1,2,3,4]
assert_equal( target, flatten( source ) )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment