Created
August 17, 2011 17:45
-
-
Save mhamrah/1152120 to your computer and use it in GitHub Desktop.
Flatten
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
#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