Skip to content

Instantly share code, notes, and snippets.

@juanfgs
Created December 5, 2017 23:02
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 juanfgs/1de28c317a6d726c284d031288ec5602 to your computer and use it in GitHub Desktop.
Save juanfgs/1de28c317a6d726c284d031288ec5602 to your computer and use it in GitHub Desktop.
Implementation
#!/usr/bin/env ruby
class Flatten
def self.flatten(array)
result = []
array.each do |x|
if x.kind_of? Array # flatten again and add the elements individually
self.flatten(x).each { |y| result.push(y) }
else
result.push(x) #add the item to the result array
end
end
return result
end
end
require 'minitest/autorun'
require 'minitest/spec'
require './flatten'
#place this file on the same folder as flatten.rb and run rake test to run these tests
describe Flatten do
before (:each) do
@cases = [ [1,2,3,4,5], [3,4,6,[3,4] ], [4,[3,4],[2,[1]]],[1,[3,4,[5,6],7,9 ],10] ]
end
it "returns an array" do
@cases.each { |x| Flatten.flatten(x).must_be_instance_of(Array) }
end
it "returns a non empty array for non empty entries" do
@cases.each { |x| Flatten.flatten(x).wont_be_empty }
end
it "returns an empty array when given empty entry" do
Flatten.flatten([]).must_be_empty
end
it "returns a non nested array" do
@cases.each do |x|
Flatten.flatten(x).each do |y|
y.wont_be_instance_of(Array)
end
end
end
it "has the same amount of elements than an array flattened with native method" do
@cases.each do |x|
Flatten.flatten(x).length.must_equal x.flatten.length
end
end
end
source 'https://rubygems.org/'
gem 'minitest'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << "spec"
t.pattern = "*_spec.rb"
t.verbose = true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment