Last active
December 28, 2018 00:17
-
-
Save tkfm-yamaguchi/af993667858dd4ce46f7f78d3ebb5541 to your computer and use it in GitHub Desktop.
flatten with loop (no recursion)
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
class Array | |
# flatten without recursion but loop | |
def myflatten! | |
i = 0 | |
while i < self.size | |
unless self[i].is_a?(Array) | |
i += 1 | |
next | |
end | |
f = self[i] | |
self.slice!(i) | |
self.insert(i, *f) | |
end | |
end | |
end | |
if __FILE__ == $0 | |
# we need these annoying lines just only to use 'assert_equal' ... sigh. | |
require "minitest" | |
include Minitest::Assertions | |
class << self | |
attr_accessor :assertions | |
end | |
self.assertions = 0 | |
# main | |
[1,["foo", ["bar"]], [[9]], []].tap do |arr| | |
arr.myflatten! | |
assert_equal(arr, [1, "foo", "bar", 9]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment