Skip to content

Instantly share code, notes, and snippets.

@dsadaka
Last active June 1, 2019 18:18
Show Gist options
  • Save dsadaka/be0261a1280f32bfde1aa126813a35f3 to your computer and use it in GitHub Desktop.
Save dsadaka/be0261a1280f32bfde1aa126813a35f3 to your computer and use it in GitHub Desktop.
Theorem Flatten Exercise

The class DansUtils contains a single method to flatten an array with an undertermined number of nested arrays.

Setup:

  1. Create a new test directory
  2. Create the two subdirectories: lib and spec
  3. Place the above files in their respective directories (see comment on first line of each file)
  4. Place the Gemfile the top level directory
  5. bundle install --path .bundle

To Test run this command at terminal prompt: $ bundle exec rspec

Which should produce:

3 examples, 0 failures

To Run in ruby console: require './lib/dans_utils.rb' utils = DansUtils.new utils.flatten([array of your choice])

# lib/dans_utils.rb
class DansUtils
# flatten - Little method to flatten an array of arrays into a single array of atomic elements
# Sample usage: dans_flatten(array_to_flatten)
# Example dans_flatten([1,2,3,[4,5,[6,7]]]) # returns [1, 2, 3, 4, 5, 6, 7]
def flatten(array, results = [])
array.each do |element|
if element.class == Array
flatten(element, results)
else
results << element
end
end
results
end
end
# spec/dans_utils.rb
require 'dans_utils'
describe DansUtils do
let(:util) { DansUtils.new }
let(:nested_array) { [1,[2,[3,4],5]] }
let(:flat_array) { [1, 2, 3, 4, 5] }
let(:empty_array) { [] }
context 'flatten' do
it "returns array of only atomic elements when passed nested arrays" do
expect(util.flatten(nested_array)).to eq(flat_array)
end
it "returns array of only atomic elements when passed flat array" do
expect(util.flatten(flat_array)).to eq(flat_array)
end
it "returns empty array when passed flat array" do
expect(util.flatten(empty_array)).to eq(empty_array)
end
end
end
source "https://rubygems.org"
gem "rspec"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment