Skip to content

Instantly share code, notes, and snippets.

@amuntasim
Created February 8, 2018 03:49
Show Gist options
  • Save amuntasim/d7cf052933fccca956bfc816f39f69d5 to your computer and use it in GitHub Desktop.
Save amuntasim/d7cf052933fccca956bfc816f39f69d5 to your computer and use it in GitHub Desktop.
Custom flatten implementation in ruby
class FlattenTest
def self.custom_flatten(array, result = [])
array.each do |item|
if item.is_a? Array
custom_flatten(item, result)
else
result << item
end
end
result
end
end
RSpec.describe FlattenTest do
context '.custom_flatten' do
it 'should flatten array of arrays' do
expected = [1, 2, 3, 4, 5, 6]
expect(FlattenTest.custom_flatten([[1, 2], 3, [4, 5, 6]])).to eq expected
end
it 'should flatten nested array of arrays' do
expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
expect(FlattenTest.custom_flatten([[1, 2], 3, [4, 5, [6, [7, 8], 9]]])).to eq expected
end
it 'should return already flatten array' do
expected = [1, 2, 3, 4]
expect(FlattenTest.custom_flatten(expected)).to eq expected
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment