Skip to content

Instantly share code, notes, and snippets.

@cristianrasch
Created December 9, 2016 13:42
Show Gist options
  • Save cristianrasch/8a5292bf9435738f6decbad2ac07a4e7 to your computer and use it in GitHub Desktop.
Save cristianrasch/8a5292bf9435738f6decbad2ac07a4e7 to your computer and use it in GitHub Desktop.
# This class provides a collection of class methods to manipulate Arrays
class ArrayUtils
class << self
# Recursively flattens its arbitrarily nested array arguement
# Warning: passing in very big arrays WILL BLOW UP THE STACK!
def flatten(arr)
_flatten(arr, [])
end
private
def _flatten(arr, res)
arr.each do |e|
if e.is_a?(Array)
_flatten(e, res)
else
res << e
end
end
res
end
end
end
require "minitest/autorun"
require "minitest/pride"
class ArrayUtilsTest < Minitest::Test
def test_flattens_a_simply_nested_array
res = ArrayUtils.flatten([1, [2], [3, 4]])
assert_equal [1, 2, 3, 4], res
end
def test_flattens_a_deeply_nested_array
res = ArrayUtils.flatten([1, [2, [3], [[4]]]])
assert_equal [1, 2, 3, 4], res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment