Skip to content

Instantly share code, notes, and snippets.

@joahking
Created November 9, 2016 16:01
Show Gist options
  • Save joahking/d52466596afa282e6dea43c121530821 to your computer and use it in GitHub Desktop.
Save joahking/d52466596afa282e6dea43c121530821 to your computer and use it in GitHub Desktop.
flatten arrays of integers without using Array.flatten
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
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