Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement