Skip to content

Instantly share code, notes, and snippets.

@mishalzaman
Last active July 2, 2019 00:40
Show Gist options
  • Select an option

  • Save mishalzaman/955ff2b6c57b7fb979a7ca436e4f4d17 to your computer and use it in GitHub Desktop.

Select an option

Save mishalzaman/955ff2b6c57b7fb979a7ca436e4f4d17 to your computer and use it in GitHub Desktop.
# Ruby version 2.5.0
# RSPEC version 3.8
# Running the tests in a console: rspec theorem.rb
# #flatten_array is a recursive method that takes in an array of arbitrary
# nesting elements and returns a flattened array.
#
# Parameters:
# arr:Array The array to flatten
# result:Array The flattened array
module Theorem
def self.flatten_array(arr, result = [])
# return arr if the array is empty or not
# an array.
return arr if arr.empty? || !arr.is_a?(Array)
# Iterate over each item in the array
arr.each do |a|
if a.class != Array
# If it isn't an array then we append the
# value to the result
result << a
else
# If it is an array then we call the
# flatten_array method recursively to
# perform the same process
self.flatten_array(a, result)
end
end
result
end
end
describe Theorem do
it 'should returned a flattened array' do
result = Theorem.flatten_array [1,[2,3],4,[5,[6,7]],8,[9,[10]]]
expect(result[0]).to eq 1
expect(result[9]).to eq 10
end
it 'should return a flattened array even if an element is empty' do
result = Theorem.flatten_array [1,[2,3],4,[],5]
expect(result[0]).to eq 1
expect(result[4]).to eq 5
end
it 'should return arr parameter value if arr is empty' do
result = Theorem.flatten_array []
expect(result.class).to eq Array
end
it 'should returned arr parameter value if arr is not not an array' do
result = Theorem.flatten_array "This is a string"
expect(result).to eq "This is a string"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment