Last active
August 29, 2015 14:26
-
-
Save thehungrycoder/edf555d7a1d383369ca6 to your computer and use it in GitHub Desktop.
Ruby's flatten implementation for Array
This file contains hidden or 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
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 |
This file contains hidden or 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
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