Skip to content

Instantly share code, notes, and snippets.

@dan-passaro
Created May 22, 2016 21:19
Show Gist options
  • Save dan-passaro/32f1e6d45e2f355acd3c8c8a3fc712ea to your computer and use it in GitHub Desktop.
Save dan-passaro/32f1e6d45e2f355acd3c8c8a3fc712ea to your computer and use it in GitHub Desktop.
A simple re-implementation of Array#flatten. Run tests with rspec
class Array
# Get a one-dimensional array by combining elements of nested arrays.
#
# ==== Examples
#
# [[3, 4], 5, [[6, 7, 8], 9]] #=> [3, 4, 5, 6, 7, 8, 9]
#
def my_flatten
result = []
self.each do |elem|
if elem.is_a?(Array)
result += elem.my_flatten
else
result << elem
end
end
result
end
end
describe "Array#my_flatten" do
it "is a no-op on an already flat array" do
expect([].my_flatten).to eq([])
expect([50].my_flatten).to eq([50])
expect([3, 4, 9].my_flatten).to eq([3, 4, 9])
end
it "always returns a new array" do
arr = []
expect(arr.my_flatten).not_to equal(arr.my_flatten)
end
it "flattens many levels of nesting" do
arr_1 = [[3], 4, 5, [[6, 7], 8], 9, 10]
expect(arr_1.my_flatten).to eq([3, 4, 5, 6, 7, 8, 9, 10])
arr_2 = [[[[[[[[[[10]]]]], 11, [[[[[[[[[[[[[[[[[12]]]]]]]]]]]]]]]]]]]]]]
expect(arr_2.my_flatten).to eq([10, 11, 12])
end
it "ignores empty arrays" do
arr = [3, [], 4, [[]], 5, [[], [], []], 6]
expect(arr.my_flatten).to eq([3, 4, 5, 6])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment