Skip to content

Instantly share code, notes, and snippets.

@juandefelix
Last active June 15, 2016 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juandefelix/b3418635d6a4a724791f753970c25849 to your computer and use it in GitHub Desktop.
Save juandefelix/b3418635d6a4a724791f753970c25849 to your computer and use it in GitHub Desktop.
Implements a method that flattens a nested array, based on recursion.

my_flatten

Implements a method that flattens a nested array, based on recursion.
Includes several tests that check the method behavior with different arrays.

# Flattens an array of arbitrarily nested arrays of integers into a flat array of integers.
# e.g. [[1,2,[3]],4] -> [1,2,3,4].
def my_flatten(ary, flattened_array=[])
return flattened_array if ary.empty?
case ary[0]
when Fixnum, Integer
flattened_array.push(ary[0])
when Array
flattened_array = my_flatten(ary[0], flattened_array)
end
return my_flatten(ary[1..-1], flattened_array)
end
my_flatten([1,2,3,[4,5]])
require File.expand_path('../../lib/my_flatten.rb', __FILE__)
describe "my_flatten" do
it 'should return an array' do
expect(my_flatten([1])).to be_an Array
end
describe 'should return an flattened array' do
it 'when passing a nested array' do
expect(my_flatten([1, [2, 3]])).to eq [1, 2, 3]
end
it 'when passing a more complex array' do
expect(my_flatten([1, [2, 3], [4, 5]])).to eq [1, 2, 3, 4, 5]
end
it 'when passing other complex nested arrays' do
expect(my_flatten([1, [2, 3, [4, 5], 6, 7]])).to eq [1, 2, 3, 4, 5, 6, 7]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment