Skip to content

Instantly share code, notes, and snippets.

@shime
Last active July 18, 2016 18:36
Show Gist options
  • Save shime/99a322d2a4a2bcf4e7c157ee8aae1ddd to your computer and use it in GitHub Desktop.
Save shime/99a322d2a4a2bcf4e7c157ee8aae1ddd to your computer and use it in GitHub Desktop.

Flattening an array

Usage

git clone [email protected]:99a322d2a4a2bcf4e7c157ee8aae1ddd.git flattening-an-array
cd flattening-an-array
bundle install
ruby tests.rb

License

MIT

source 'https://rubygems.org'
gem "minitest"
require "minitest/autorun"
# Public: Irons out an array.
#
# array - the array to be ironed out
#
# Examples
#
# iron([1, [2]])
# # => [1, 2]
#
# iron([1, [2, [3]]])
# # => [1, 2, 3]
#
# Returns the ironed out Array.
def iron(array, flattened = [])
array.each do |element|
if element.is_a?(Array)
iron(element, flattened)
else
flattened << element
end
end
flattened
end
describe "#iron" do
it "iron([]) => []" do
iron([]).must_equal []
end
it "iron([1]) => [1]" do
iron([1]).must_equal [1]
end
it "iron([1, 2, 3]) => [1, 2, 3]" do
iron([1, 2, 3]).must_equal [1, 2, 3]
end
it "iron([[1]]) => [1]" do
iron([1]).must_equal [1]
end
it "iron([1, [2]]) => [1, 2]" do
iron([1, [2]]).must_equal [1, 2]
end
it "iron([1, [2, [3]]]) => [1, 2, 3]" do
iron([1, [2, [3]]]).must_equal [1, 2, 3]
end
it "iron([1, [2, [3, [4, [5, [6, [7]]]]]]]) => [1, 2, 3, 4, 5, 6, 7]" do
iron([1, [2, [3, [4, [5, [6, [7]]]]]]]).must_equal [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