Created
June 6, 2019 01:08
-
-
Save guilpejon/fdda183f41ea6ef994fe94c77763138a to your computer and use it in GitHub Desktop.
Array Flattener + Tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
class ArrayFlattener | |
def initialize(array) | |
@array = array | |
end | |
def call | |
raise unless array.is_a? Array | |
# The next line does the following: | |
# 1 - converts the array to a string | |
# 2 - scans the code looking for numbers using regex | |
# 3 - convert the array of string numbers found to an array of integers | |
array.to_s.scan(/\d+/).map(&:to_i) | |
end | |
private | |
attr_reader :array | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative 'array_flattener' | |
require 'test/unit' | |
class TestArrayFlattener < Test::Unit::TestCase | |
def test_base | |
assert_equal([1,2,3,4], ArrayFlattener.new([[1,2,[3]],4]).call) | |
end | |
def test_no_change | |
assert_equal([1,2,3,4], ArrayFlattener.new([1,2,3,4]).call) | |
end | |
def test_simple | |
assert_equal([1,2,3,4], ArrayFlattener.new([[1],[2],[3],[4]]).call) | |
end | |
def test_big_numbers | |
assert_equal([111,222222,33333333,4444444], ArrayFlattener.new([[111,222222,[33333333]],4444444]).call) | |
end | |
def test_multiple_levels | |
assert_equal([1,2,3,4], ArrayFlattener.new([[[[[1],[2]],[3]],[4]]]).call) | |
end | |
def test_typecheck | |
assert_raise( RuntimeError ) { ArrayFlattener.new(1).call } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment