Created
July 15, 2017 12:28
-
-
Save niyando/6f51f68ac0decaf980849be965e06051 to your computer and use it in GitHub Desktop.
Custom instance method of Array class in Ruby to flatten it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def flatten_it(result = []) | |
self.each do |value| | |
value.is_a?(Array) ? value.flatten_it(result) : (result << value) | |
end | |
result | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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