Skip to content

Instantly share code, notes, and snippets.

@thehungrycoder
Last active August 29, 2015 14:26
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 thehungrycoder/edf555d7a1d383369ca6 to your computer and use it in GitHub Desktop.
Save thehungrycoder/edf555d7a1d383369ca6 to your computer and use it in GitHub Desktop.
Ruby's flatten implementation for Array
require 'rspec' #gem install rspec
require './flatten'
describe 'myflatten' do
it 'makes array single dim regardless of nesting' do
expect([1,2,3].myflatten).to eq([1,2,3])
expect([[1,2,3]].myflatten).to eq([1,2,3])
expect([[[1,2,3]]].myflatten).to eq([1,2,3])
expect([[1,2, [3]], [[[[[[[[[4]]]]]]]]], [[5, [6]], 7]].myflatten).to eq([1,2,3,4,5,6,7])
end
end
class Array
def myflatten
newArr = []
self.each do |item|
if item.is_a?(Array)
newArr = newArr + item.myflatten
else
newArr.push(item)
end
end
newArr
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment