Skip to content

Instantly share code, notes, and snippets.

@niyando
Created July 15, 2017 12: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 niyando/6f51f68ac0decaf980849be965e06051 to your computer and use it in GitHub Desktop.
Save niyando/6f51f68ac0decaf980849be965e06051 to your computer and use it in GitHub Desktop.
Custom instance method of Array class in Ruby to flatten it
class Array
def flatten_it(result = [])
self.each do |value|
value.is_a?(Array) ? value.flatten_it(result) : (result << value)
end
result
end
end
require 'minitest/autorun'
require './array'
describe Array do
before do
@nested_array = [1, [1,2],[3,[4,5],[]]]
end
describe "#flatten_it" do
it "returns a flattened array" do
assert_equal [1,1,2,3,4,5], @nested_array.flatten_it
end
test_cases = [
[ 1, 1, 1, 1, 1, 1, 1, 1 ],
[[3,4,[],5],5],
[:apple, :banana, [1,[]], 'brocolli'],
[],
[nil, nil, [[[1]]]],
[[1,2,[3]],4],
[1,2,3,"banana",[1,2,3],[]]
]
test_cases.each do |arr|
it "#{arr}.flatten_it should not have a nested array" do
assert arr.flatten_it.none? {|v| v.is_a? Array}
end
it "#{arr}.flatten it should match ruby's flatten method" do
assert_equal arr.flatten, arr.flatten_it
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment