Skip to content

Instantly share code, notes, and snippets.

@Skillvendor
Created February 25, 2018 13:33
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 Skillvendor/9ac6b5e139c1d9775b51bcd757dec779 to your computer and use it in GitHub Desktop.
Save Skillvendor/9ac6b5e139c1d9775b51bcd757dec779 to your computer and use it in GitHub Desktop.
Ruby Array Flattener
require 'rspec'
# class used to flatten arrays
# Input:
# @param [Array] arr: the array that needs flattening
# Output when flatten method is invoked:
# @param [Array] flattened array
class Flattener
def initialize(arr)
raise 'Pass an array' unless arr.kind_of? Array
@arr = arr
end
def flatten
get_flattened_array @arr
end
private
def get_flattened_array arr
arr.reduce([]) do |result, item|
if item.is_a? Array
result + get_flattened_array(item)
else
result << item
end
end
end
end
require './spec_helper'
require './flattener'
RSpec.describe Flattener do
context 'valid input' do
TEST_CASES = [
[1, 2, 3],
[],
[1, 2, 3, [1, 2, 3]],
[1, [1], [[1]], [[2], [3]]]
]
TEST_CASES.each do |test_case|
#context needed otherwise it can retain values from other context and we get random failures
context "#{test_case}" do
subject { Flattener.new(test_case) }
it "returns the right result for #{test_case}" do
expect(subject.flatten).to eq(test_case.flatten)
end
end
end
end
context 'invalid input' do
subject { Flattener.new('something') }
it 'checks if array was passed' do
expect {
subject.flatten
}.to raise_error('Pass an array')
end
end
end
source 'https://rubygems.org'
gem 'rspec', '~> 3.4'
require 'rspec'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment