Skip to content

Instantly share code, notes, and snippets.

@taboularasa
Created June 25, 2016 07:48
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 taboularasa/4159b45b54c9a110d02e4dea2244227e to your computer and use it in GitHub Desktop.
Save taboularasa/4159b45b54c9a110d02e4dea2244227e to your computer and use it in GitHub Desktop.
flatten an Array
require 'minitest/autorun'
##
# Implement flatten
#
# ruby -Ilib:test flatten.rb
def flatten(accumulator, element)
if element.is_a? Array
element.each {|e| flatten(accumulator, e)}
else
accumulator << element
end
end
class TestFlatten < Minitest::Test
def test_handles_nested_array
input = [[1,2,[3]],4]
result = []
expected = [1,2,3,4]
flatten(result, input)
assert_equal(result, expected)
end
def test_handles_flat_array
input = [1,2,3,4]
result = []
expected = [1,2,3,4]
flatten(result, input)
assert_equal(result, expected)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment