Skip to content

Instantly share code, notes, and snippets.

@naifen
Created June 17, 2019 23:17
Show Gist options
  • Select an option

  • Save naifen/d4fbf715f322a0cb7db2c9b2cc14f2f1 to your computer and use it in GitHub Desktop.

Select an option

Save naifen/d4fbf715f322a0cb7db2c9b2cc14f2f1 to your computer and use it in GitHub Desktop.
a ruby method that flatten an array with associated test
def flatten_array(ary, result = [])
raise 'Please pass an array as argument' unless ary.kind_of? Array
# if an element in the given array is an array, recursively call flatten_array
# on the element, otherwise push it into the result array
ary.each do |ele|
if ele.class == Array
flatten_array(ele, result)
else
result << ele
end
end
result
end
require 'test/unit'
class FlattenArrayTest < Test::Unit::TestCase
ARRAY1 = [1, [2, 3, [4, 5]]]
RESULT1 = [1, 2, 3, 4, 5]
ARRAY2 = [[1, 2, [3]], 4]
RESULT2 = [1, 2, 3, 4]
def test1
result = flatten_array(ARRAY1)
assert_equal RESULT1, result, "Expect the result to be #{RESULT1}"
end
def test2
result = flatten_array(ARRAY2)
assert_equal RESULT2, result, "Expect the result to be #{RESULT2}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment