Last active
May 30, 2018 18:52
-
-
Save davingee/e8435e3f37d7221f61b9f69e0ae67df6 to your computer and use it in GitHub Desktop.
This is an Array instance method that flattens any kind of array or array of arrays that contain integers (Fixnum)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec' | |
class Array | |
def flatten_ints(all=[]) | |
self.each do |item| | |
if item.class == Array | |
item.flatten_ints(all) | |
else | |
unless item.class == Fixnum | |
raise TypeError.new "This Methos is only for flattening Fixnums" | |
end | |
all << item | |
end | |
end | |
all | |
end | |
end | |
module ArraySpecHelper | |
def array(n) | |
n | |
end | |
def array_of_array(n) | |
[n] | |
end | |
def array_of_array_of_array(n) | |
[[n]] | |
end | |
# this helper method can be called with an array of one or all of the preset variables | |
# it iterates over 20 times and calls send on the current sampled bag. | |
# one can call array_types([:array]) and expect a simple array | |
# calling it with all three will give you a sample of all types | |
def array_types(bag = %i[array array_of_array array_of_array_of_array]) | |
(1..20).to_a.map{ |n| send(bag.sample, n) } | |
end | |
end | |
describe Array do | |
include ArraySpecHelper | |
context "flatten_ints" do | |
context 'success' do | |
it "keeps an already flattened array the same" do | |
# array_types([:array]).flatten_ints.each do |n| | |
# expect(n.class).to eq(Fixnum) | |
# end | |
expect(array_types([:array]).flatten_ints).to eq((1..20).to_a) | |
end | |
it "flattens out an array of arrays" do | |
expect(array_types([:array_of_array]).flatten_ints).to eq((1..20).to_a) | |
end | |
it "flattens out an array of array of arrays" do | |
expect(array_types([:array_of_array_of_array]).flatten_ints).to eq((1..20).to_a) | |
end | |
it "flattens out a mixed bag of arrays" do | |
expect(array_types.flatten_ints).to eq((1..20).to_a) | |
end | |
end | |
context 'failure' do | |
it "only works for integers" do | |
expect { %w[a b 3].flatten_ints }.to raise_error(TypeError, 'This Methos is only for flattening Fixnums') | |
end | |
end | |
end | |
end |
Oops looking on my phone. Consider restructuring that line to be shorter or put the unless
on the line above
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any code after the
raise
won’t be executed