Skip to content

Instantly share code, notes, and snippets.

@stevecj
Last active March 30, 2016 08:49
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 stevecj/a24339e6a34baf80755dda8997799319 to your computer and use it in GitHub Desktop.
Save stevecj/a24339e6a34baf80755dda8997799319 to your computer and use it in GitHub Desktop.
Coding exercise: Flatten an array in Ruby w/o using `Array#flatten`
module ArrayUtils
def self.flatten(array, result=[])
array = Array(array)
array.each do |entry|
case entry
when Array
flatten entry, result
else
result << entry
end
end
result
end
def self.non_recursive_flatten(array)
result = []
enum = array.each
stack = []
loop do
begin
entry = enum.next
case entry
when Array
stack << enum
enum = entry.each
else
result << entry
end
rescue StopIteration
enum = stack.pop
break unless enum
end
end
result
end
end
p ArrayUtils.flatten( [[1,2,[3]],4] )
# => [1, 2, 3, 4]
p ArrayUtils.non_recursive_flatten( [[1,2,[3]],[],4] )
# => [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment