Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Last active December 28, 2018 00:17
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 tkfm-yamaguchi/af993667858dd4ce46f7f78d3ebb5541 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/af993667858dd4ce46f7f78d3ebb5541 to your computer and use it in GitHub Desktop.
flatten with loop (no recursion)
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