Skip to content

Instantly share code, notes, and snippets.

@guilpejon
Created June 6, 2019 01:08
Show Gist options
  • Save guilpejon/fdda183f41ea6ef994fe94c77763138a to your computer and use it in GitHub Desktop.
Save guilpejon/fdda183f41ea6ef994fe94c77763138a to your computer and use it in GitHub Desktop.
Array Flattener + Tests
#!/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
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