Skip to content

Instantly share code, notes, and snippets.

@coolsoftwaretyler
Last active May 28, 2019 17:25
Show Gist options
  • Select an option

  • Save coolsoftwaretyler/0b2e8a5fc41f77ff0ad9221662ff1f2c to your computer and use it in GitHub Desktop.

Select an option

Save coolsoftwaretyler/0b2e8a5fc41f77ff0ad9221662ff1f2c to your computer and use it in GitHub Desktop.

Revisions

  1. coolsoftwaretyler revised this gist May 28, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion flatten.rb
    Original file line number Diff line number Diff line change
    @@ -30,7 +30,7 @@ def flatten(array, results = [])
    it 'asks user for an array when provided nil' do
    expect(flatten(nil)).to eq('Please provide an array')
    end
    it ' an empty array' do
    it 'handles an empty array' do
    expect(flatten([])).to eq([])
    end
    it 'handles a flat array' do
  2. coolsoftwaretyler revised this gist May 28, 2019. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion flatten.rb
    Original file line number Diff line number Diff line change
    @@ -16,9 +16,10 @@ def flatten(array, results = [])
    results << item
    end
    end
    # `p` is the equivalent of
    # Return the results array
    results
    else
    # Return a message asking user to provide an array
    'Please provide an array'
    end
    end
  3. coolsoftwaretyler created this gist May 28, 2019.
    41 changes: 41 additions & 0 deletions flatten.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    # Use RSpec for testing https://rspec.info/
    require 'rspec'

    # Define the flatten function, we'll use it recursively
    # On the initial run, set `results` to an empty array
    def flatten(array, results = [])
    # Check that array is not nil
    if array
    # For each item in the array, check if it's a nested array
    array.each do |item|
    # If the item is an array, run `flatten()` on it, and pass in the results array as well
    if item.class == Array
    flatten(item, results)
    else
    # If the item isn't an array, toss it in the results array
    results << item
    end
    end
    # `p` is the equivalent of
    results
    else
    'Please provide an array'
    end
    end

    # Unit tests with RSpec
    # Be sure to run `gem install rspec` and `rspec flatten.rb` in the directory
    describe 'Flatten' do
    it 'asks user for an array when provided nil' do
    expect(flatten(nil)).to eq('Please provide an array')
    end
    it ' an empty array' do
    expect(flatten([])).to eq([])
    end
    it 'handles a flat array' do
    expect(flatten([1,2,3])).to eq([1,2,3])
    end
    it 'handles a nested array' do
    expect(flatten([[1,2,[3]],4])).to eq([1,2,3,4])
    end
    end