Created
November 9, 2016 16:01
-
-
Save joahking/d52466596afa282e6dea43c121530821 to your computer and use it in GitHub Desktop.
flatten arrays of integers without using Array.flatten
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 Flatten | |
def initialize(array) | |
@array = array | |
end | |
def flatten(array = @array) | |
if array.is_a? Integer | |
[array] | |
else | |
array.inject([]) { |memo, elem| memo + flatten(elem) } | |
end | |
end | |
end |
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
require 'minitest/autorun' | |
require_relative 'flatten' | |
class FlattenTest < Minitest::Test | |
def test_flatten | |
assert_equal [1,2,3,4], Flatten.new([[1,2,[3]],4]).flatten | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment