Skip to content

Instantly share code, notes, and snippets.

@mhamrah
Created August 17, 2011 17:45
Show Gist options
  • Save mhamrah/1152120 to your computer and use it in GitHub Desktop.
Save mhamrah/1152120 to your computer and use it in GitHub Desktop.
Flatten
#Michael Hamrah
require 'rspec'
def flatten(input)
array = []
input.each { |x| (x.respond_to? :each) ? array.concat(flatten(x)) : array.push(x) }
array
end
describe "Flatten" do
it "returns an array with the same items as input" do
data = [3, 2, 1]
result = flatten(data)
result.count.should == data.count
result.should include(data[0])
end
it "can flatten an array containing multiple arrays" do
data = [[1, 2], 3, [4, 5, 6], 7]
result = flatten(data)
result.count.should == 7
result.should include(2)
result.should include(7)
end
it "can flatten multiple nested arrays" do
data = [1, [2, [3, 4], 5], 6, 7]
result = flatten(data)
result.count.should == 7
result.should include(4)
result.should include(5)
result.should include(7)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment