Created
March 12, 2016 07:47
-
-
Save murphybytes/914c9c9778b4f0cdaddd to your computer and use it in GitHub Desktop.
Flatten
This file contains hidden or 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
| #!/usr/bin/env ruby | |
| # Adds new method to the Array class that flattens arrays of ints | |
| # non-integer elements in the array will raise | |
| # an exception. | |
| class Array | |
| def flatten_ints | |
| flat = [] | |
| self.each do |elt| | |
| if elt.is_a? Array | |
| flat.concat elt.flatten_ints | |
| else | |
| raise "Non integer in array" if !elt.is_a? Integer | |
| flat << elt | |
| end | |
| end | |
| flat | |
| end | |
| end | |
| test = [[1,2,[3]],4] | |
| raise "Error #{test}" unless test.flatten.eql? test.flatten_ints | |
| test = [] | |
| raise "Error #{test}" unless test.flatten.eql? test.flatten_ints | |
| test = [1,[],[3,4,[5,[6,7],8]]] | |
| raise "Error #{test}" unless test.flatten.eql? test.flatten_ints | |
| test = [[[1,2,3]]] | |
| raise "Error #{test}" unless test.flatten.eql? test.flatten_ints | |
| test = [[[]]] | |
| raise "Error #{test}" unless test.flatten.eql? test.flatten_ints | |
| begin | |
| [1,2,[3,"x"]].flatten_ints | |
| raise "an exception should have been thrown but was not" | |
| rescue | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment