Skip to content

Instantly share code, notes, and snippets.

@vedant1811
Last active June 2, 2019 04:02
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 vedant1811/e2f7d981a2a13d70f547d26d60a9377f to your computer and use it in GitHub Desktop.
Save vedant1811/e2f7d981a2a13d70f547d26d60a9377f to your computer and use it in GitHub Desktop.
Flatten Array
def flatten_array(array)
ans = []
array&.each do |element|
if element.is_a? Array
ans += flatten_array(element)
else
ans << element
end
end
ans
end
#
# run tests using `rspec flatten_spec.rb`
require './flatten'
RSpec.describe "flatten" do
it do
input = [[1,2,[3]],4]
output = [1,2,3,4]
expect(flatten_array(input)).to eq(output)
end
it do
input = [[1,2,[]],4]
output = [1,2,4]
expect(flatten_array(input)).to eq(output)
end
it do
input = [[1,[[],[],[],[]],2,4]]
output = [1,2,4]
expect(flatten_array(input)).to eq(output)
end
it do
input = []
output = []
expect(flatten_array(input)).to eq(output)
end
it do
input = nil
output = []
expect(flatten_array(input)).to eq(output)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment