Last active
March 24, 2017 09:34
-
-
Save knagode/dc132d7e2c5d6e2d06574deeb8f29003 to your computer and use it in GitHub Desktop.
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
# Method which flattens the array:[[1,2,[3]],4] -> [1,2,3,4] | |
module Flattenizer | |
def flattenize array | |
return [array] unless array.kind_of?(Array) # result of method is always array | |
result = [] | |
array.each do |item| | |
flattenize(item).each do |r| # ensure that result will not be nested | |
result << r | |
end | |
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 './flattenizer' | |
include Flattenizer | |
class TestFlattenize < Minitest::Test | |
def test_not_nested_array | |
assert_equal [1, 2, 3], flattenize([1, 2, 3]) | |
end | |
def test_nested_array | |
assert_equal [1, 2, 3], flattenize([1, [2, [3]]]) | |
end | |
def test_if_integer_is_converted_into_array | |
assert_equal [1], flattenize(1) | |
end | |
def test_if_method_works_with_empty_array | |
assert_equal [], flattenize([]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To test it in console ;)