Skip to content

Instantly share code, notes, and snippets.

@alip
Created June 16, 2016 07:40
Show Gist options
  • Select an option

  • Save alip/8a8d456b99f709651c191f4a22b8ff3f to your computer and use it in GitHub Desktop.

Select an option

Save alip/8a8d456b99f709651c191f4a22b8ff3f to your computer and use it in GitHub Desktop.
Flatten array without Array#flatten
#!/usr/bin/env ruby
# coding: utf-8
def flatten(array)
Array.new.tap do |flat_array|
array.each do |item|
case item
when Numeric
flat_array << item
when Enumerable
flat_array.concat(flatten(item))
else
fail "Unexpected item #{item.class}, must be an Integer or an Enumerable"
end
end
end
end
x = [1,2,3,[4,5]]
y = [1,2,3,[4,5], [6, [7,8]]]
z = [1,2,3,[4,5], [5, [7,8], [[[8, 9, [7]]]]]]
puts flatten(x).join(',')
puts flatten(y).join(',')
puts flatten(z).join(',')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment