Created
June 22, 2017 23:28
-
-
Save felipero/f2b7ab792c82ccee99c179be9855913e to your computer and use it in GitHub Desktop.
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 ArrayTools | |
def self.flat_array(array = []) | |
array.each_with_object([]) do |item, flat_array| | |
next if item.kind_of? String | |
flat_array.push *(item.kind_of?(Array) ? flat_array(item) : item) | |
end | |
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
RSpec.describe ArrayTools do | |
describe '.flat_array' do | |
it 'flattens 1 level nested array' do | |
expect(Group.flat_array([1, 2, 3, [9, 8], 7])).to eq [1, 2, 3, 9, 8, 7] | |
end | |
it 'flattens an empty array' do | |
expect(Group.flat_array([])).to eq [] | |
end | |
it 'flattens a nested empty array' do | |
expect(Group.flat_array([1, []])).to eq [1] | |
end | |
it 'flattens a 2 leves nested array' do | |
expect(Group.flat_array([1, [[3, 4]]])).to eq [1, 3, 4] | |
end | |
it 'flattens arrays with string' do | |
expect(Group.flat_array(['sbrubles', 2, 3, [9, 8], 7])).to eq [2, 3, 9, 8, 7] | |
expect(Group.flat_array([1, 2, 3, ['bla', 9, 8], 7])).to eq [1, 2, 3, 9, 8, 7] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment