Skip to content

Instantly share code, notes, and snippets.

@jaeming
Last active September 26, 2016 20:36
Show Gist options
  • Save jaeming/3ec2c040ac69d9e01753ee502e97db6f to your computer and use it in GitHub Desktop.
Save jaeming/3ec2c040ac69d9e01753ee502e97db6f to your computer and use it in GitHub Desktop.

#Pancake.flatten

###about:

Returns a new array that is a one-dimensional flattening of nested arrays (recursively).

###usage:

Pancake.flatten(array)

###examples:

a = [1, 2, [3, 4], 'five']
b = [1, 2, [[3, 4], ['five', [6, 7]], 8]]
Pancake.flatten(a)  #returns [1, 2, 3, 4, 'five']
Pancake.flatten(b)  #returns [1, 2, 3, 4, "five", 6, 7, 8]`

###specs: Run bundle install to install minitest dependencies. Then run ruby pancake_spec.rb

source "https://rubygems.org"
gem "minitest"
class Pancake
def self.flatten(list)
flattened = []
list.map do |item|
flattened += (item.is_a?(Array) ? Pancake.flatten(item) : [item])
end
flattened
end
end
require_relative 'pancake'
require 'minitest/autorun'
class TestPancake < Minitest::Test
def setup
@nested_array = [1, 2, [3, 4], 'five']
@deeply_nested_array = [1, 2, [[3, 4], ['five', [6, 7]], 8]]
end
def test_flattens_nested_array
assert_equal [1, 2, 3, 4, 'five'], Pancake.flatten(@nested_array)
end
def test_flattens_deeply_nested_array
assert_equal [1, 2, 3, 4, "five", 6, 7, 8], Pancake.flatten(@deeply_nested_array)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment