Created
March 7, 2018 18:39
-
-
Save stephenbaidu/52039617c1d1d55147833b1964ea8dbc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class FlattenArray | |
attr_reader :result | |
def initialize(array) | |
@array = array | |
end | |
def call | |
@result = flatten(@array) || [] | |
@result | |
end | |
private | |
def flatten(element) | |
return [element] unless element.is_a?(Array) | |
element.map{|e| flatten(e) }.inject(:+) | |
end | |
end | |
class TestFlattenArray | |
def self.run | |
# test case 1 | |
array = [] | |
flatten_array = FlattenArray.new(array).call | |
assertion = flatten_array == [] | |
puts "Test case 1: #{assertion} should be true" | |
# test case 2 | |
array = [[1,2,[3]],4] | |
flatten_array = FlattenArray.new(array).call | |
assertion = flatten_array == [1, 2, 3, 4] | |
puts "Test case 2: #{assertion} should be true" | |
end | |
end | |
TestFlattenArray.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment