Skip to content

Instantly share code, notes, and snippets.

@virolea
Created April 28, 2016 16:19
Show Gist options
  • Select an option

  • Save virolea/a588f2cf85b6faca04e56fcf5cd73b65 to your computer and use it in GitHub Desktop.

Select an option

Save virolea/a588f2cf85b6faca04e56fcf5cd73b65 to your computer and use it in GitHub Desktop.
Flatten an array of nest arrays
def flatten(array)
return "Input must be an array" if !array.kind_of?(Array)
array.reduce([]) do |res, el|
Array === el ? res + flatten(el) : res << el
end
end
require 'flatten'
describe '#flatten' do
it "must raise an error if the input is not an array" do
input = "string"
expect(flatten(input)).to eq("Input must be an array")
end
it "must raise an error if the input is null" do
input = nil
expect(flatten(input)).to eq("Input must be an array")
end
it "must return an empty array if it is given an empty array as an input" do
empty_array = []
expect(flatten(empty_array)).to eq([])
end
it "must flatten an array of nested integers" do
array = [1,2,[3,[4,5]],[6,[7]],[8,9,10]]
expect(flatten(array)).to eq([1,2,3,4,5,6,7,8,9,10])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment