Skip to content

Instantly share code, notes, and snippets.

@knagode
Last active March 24, 2017 09:34
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 knagode/dc132d7e2c5d6e2d06574deeb8f29003 to your computer and use it in GitHub Desktop.
Save knagode/dc132d7e2c5d6e2d06574deeb8f29003 to your computer and use it in GitHub Desktop.
# 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
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
@knagode
Copy link
Author

knagode commented Mar 24, 2017

ruby -Ilib:test flattenizer_test.rb

To test it in console ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment