Created
September 28, 2016 19:34
-
-
Save joshnabbott/ebcec87b2087a6b5a9af27d8ebaf5a46 to your computer and use it in GitHub Desktop.
Method to flatten a multi-dimensional array written in Ruby
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 | |
Array.class_eval { | |
def squarsh | |
return self if empty? | |
element = self.pop | |
if element.is_a?(Array) | |
self.squarsh + element.squarsh | |
else | |
self.squarsh << element | |
end | |
end | |
} | |
puts <<-text | |
=========================================== | |
================ TESTING ================== | |
text | |
arrays_to_test = [ | |
[1,2,3,4], | |
[1,[2,3]], | |
[[]], | |
[[1],[[2]],[[[3]]],[[[[4]]]],[[[[[5]]]]]] | |
] | |
arrays_to_test.each do |array| | |
dup = array.dup | |
right = array.flatten | |
test = dup.squarsh | |
puts "TEST: #{ test } should be equal to #{ right }?" | |
puts (right == test ? "\033[42mPass\033[0m" : "\033[41mFail\033[0m") | |
end | |
puts <<-text | |
=============== END TEST ================== | |
=========================================== | |
text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment