Skip to content

Instantly share code, notes, and snippets.

@bgswan
Created April 22, 2016 02:27
Show Gist options
  • Save bgswan/cf40ef3708f56037c5ef349b39e6b976 to your computer and use it in GitHub Desktop.
Save bgswan/cf40ef3708f56037c5ef349b39e6b976 to your computer and use it in GitHub Desktop.
Example of flattening an Array.
module ArrayHelper
# Returns a new Array which is the result
# flattening any nested arrays.
#
# @param [Array] the array to flatten
# @param [Array] the array to append results to.
#
# @return [Array] the flattened array.
#
# @raise [ArgumentError] if the array to flatten is `nil`.
#
# @example
# flatten([[1,2,[3]],4]) #=> [1,2,3,4]
#
def flatten(a, result=[])
raise ArgumentError, 'Array cannot be nil' if a.nil?
a.each do |item|
if item.is_a? Array
flatten(item, result)
else
result << item
end
end
result
end
end
require 'minitest/autorun'
class FlattenTest < MiniTest::Unit::TestCase
include ArrayHelper
def test_nil
assert_raises ArgumentError do
flatten(nil)
end
end
def test_empty_array
assert_equal [], flatten([])
end
def test_already_flat_array
assert_equal [1, 2, 3], flatten([1, 2, 3])
end
def test_single_nested_array
assert_equal [1, 2, 3, 4], flatten([1, [2, 3], 4])
end
def test_multiple_single_nested_arrays
assert_equal [1, 2, 3, 4], flatten([[1], [2, 3], 4])
end
def test_multi_level_nested_array
assert_equal [1, 2, 3, 4], flatten([[1,2,[3]],4])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment