Skip to content

Instantly share code, notes, and snippets.

@richardsondx
Last active January 8, 2020 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardsondx/409abb37d0aa75afb7523399b1b29601 to your computer and use it in GitHub Desktop.
Save richardsondx/409abb37d0aa75afb7523399b1b29601 to your computer and use it in GitHub Desktop.
Util to Flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]

ArrayUtil

I wrote a class with a custom :flatten method in Ruby similar to [1,2,3].flatten This method recursively flatten an Array

Prerequisite

You'll need:

  • ruby
  • minitest

The test was written using Minitest. You can install minitest in the command line by typing:

$ gem instal minitest

Usage

You can try the method directly in the ruby console

Start irb

$ irb

Require ArrayUtil

> require './array_util.rb'

Pass the array as an argument of ArrayUtil flatten method

> ArrayUtil.flatten([1,2,3])

Test

To run the test in the command line type:

$ ruby array_util_test

# Flatten an array recursively
class ArrayUtil
def self.flatten(array)
flatten_array = []
array.each do |item|
if item.is_a? Array
flatten_array.concat(flatten(item))
else
flatten_array << item
end
end
flatten_array
end
end
#! /usr/bin/env ruby
require 'minitest/autorun'
require_relative 'array_util.rb'
# Test ArrayUtil
class ArrayUtilTest < Minitest::Test
def test_flatten
assert_equal [1, 2, 3, 4, 5, 6, 7],
ArrayUtil.flatten([1, 2, [3, 4, [5, 6]], 7])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment