Skip to content

Instantly share code, notes, and snippets.

@felipero
Created June 22, 2017 23:28
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 felipero/f2b7ab792c82ccee99c179be9855913e to your computer and use it in GitHub Desktop.
Save felipero/f2b7ab792c82ccee99c179be9855913e to your computer and use it in GitHub Desktop.
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
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