Skip to content

Instantly share code, notes, and snippets.

@stevecj stevecj/flatten-it.rb
Last active Mar 30, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.