Skip to content

Instantly share code, notes, and snippets.

@lucasmedeirosleite
Last active December 16, 2019 21:56
Show Gist options
  • Save lucasmedeirosleite/4412c529df5e0d78b31b712de3631d27 to your computer and use it in GitHub Desktop.
Save lucasmedeirosleite/4412c529df5e0d78b31b712de3631d27 to your computer and use it in GitHub Desktop.
Flatten implementation in ruby without using it own method.
require 'rspec'
class Flattener
def initialize(array)
raise 'An Array must be passed' unless array.kind_of? Array
@array = array
end
def flatten
do_flatten(@array)
end
private
def do_flatten(current_array)
acc = []
current_array.each do |element|
if element.kind_of? Array
acc += do_flatten(element)
else
acc << element
end
end
acc
end
end
RSpec.describe Flattener do
it 'flattens [1, 3, 3]' do
expect(Flattener.new([1, 3, 4]).flatten).to eq [1, 3, 4]
end
it 'flattens [1, [2], 3]' do
expect(Flattener.new([1, [2], 3]).flatten).to eq [1, 2, 3]
end
it 'flattens [1, 2, [ 3, 4, [5]]], 7]' do
numbers = [1, 2, [ 3, 4, [5]], 7]
expect(Flattener.new(numbers).flatten).to eq [1, 2, 3, 4, 5, 7]
end
it 'checks if array was passed' do
expect {
Flattener.new(double)
}.to raise_error('An Array must be passed')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment