Skip to content

Instantly share code, notes, and snippets.

@gcasa
Created September 21, 2017 04:00
Show Gist options
  • Save gcasa/62ab73bb44aa59ca3479c59f49eb3aef to your computer and use it in GitHub Desktop.
Save gcasa/62ab73bb44aa59ca3479c59f49eb3aef to your computer and use it in GitHub Desktop.
Recursively flatten an array without using built-in methods.
#!/bin/ruby
require 'test/unit'
require 'test/unit/ui/console/testrunner'
class Array
# Flatten the Array of nested arrays recursively
# without using any pre-written methods.
def flatten_array(result = [])
self.each do |element|
if element.instance_of?( Array )
element.flatten_array(result)
else
result.push(element)
end
end
result
end
end
class ArrayTest < Test::Unit::TestCase
# Main test case
def test_array
array = [[1,2,[3]],4]
expected_result = [1,2,3,4]
actual_result = array.flatten_array
puts "Result: #{actual_result}"
assert_equal expected_result, actual_result, 'Arrays are not equal!'
end
def test_array_individual_nesting
array = [[[1],[2],[3]],[4]]
expected_result = [1,2,3,4]
actual_result = array.flatten_array
puts "Result: #{actual_result}"
assert_equal expected_result, actual_result, 'Arrays are not equal!'
end
def test_array_multiple_nesting
array = [[[1],[[[2]]],[3]],[4]]
expected_result = [1,2,3,4]
actual_result = array.flatten_array
puts "Result: #{actual_result}"
assert_equal expected_result, actual_result, 'Arrays are not equal!'
end
end
# Run it...
my_tests = Test::Unit::TestSuite.new('Array tests')
my_tests << ArrayTest.new('test_array')
my_tests << ArrayTest.new('test_array_individual_nesting')
my_tests << ArrayTest.new('test_array_multiple_nesting')
Test::Unit::UI::Console::TestRunner.run(my_tests)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment