Skip to content

Instantly share code, notes, and snippets.

@waclock
Created July 9, 2019 23:48
Show Gist options
  • Save waclock/cd4142e96456f348cf5d40fa3c14f941 to your computer and use it in GitHub Desktop.
Save waclock/cd4142e96456f348cf5d40fa3c14f941 to your computer and use it in GitHub Desktop.
Ruby manual flatten method
# frozen_string_literal: true
##
# This class is an auxiliary class with helpful methods useful for common and necessary operations.
require 'rspec/autorun'
class Aux
# Helper method to flatten deeply nested arrays
# Input can either be a deeply nested array, or even an element.
# @return [Array] of elements
def self.flatten(input, result = [])
if input.is_a? Array
input.each do |element|
Aux.flatten(element, result)
end
else
result << input
end
result
end
end
# In order to use rspec, you must install the gem rspec first, run: gem install rspec
describe Aux, '.flatten' do
it 'should return a flat array' do
unflattened_array = [[1, 2, [3]], 4]
flattened_array = Aux.flatten(unflattened_array)
expect(flattened_array.length).to equal(4)
end
it "should return an array of length 1 if it's a single element" do
unflattened_array = 3
flattened_array = Aux.flatten(unflattened_array)
expect(flattened_array.length).to equal(1)
expect(flattened_array).to be_instance_of(Array)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment