Skip to content

Instantly share code, notes, and snippets.

@ma11hew28
Created September 9, 2010 05:04
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 ma11hew28/571402 to your computer and use it in GitHub Desktop.
Save ma11hew28/571402 to your computer and use it in GitHub Desktop.
Ruby implementation of flatten for nested arrays
#!/usr/bin/env ruby
class Array
def mattflat
if empty? # base case
self
else
tail = pop
if tail.kind_of? Array
mattflat + tail.mattflat
else
mattflat << tail
end
end
end
end
class FunArray < Array
def play
puts "have fun!"
end
end
puts "Specs"
puts "====="
f = FunArray.new(2)
f[0] = 1
f[1] = FunArray.new(2)
f[1][0] = 2
f[1][1] = 3
cases = [
[],
[1],
[1, 2, 3],
[1, [2, 3]],
[1, [2, [3, 4]]],
[1, [2, [3, 4], [5, 6, [7, 8, [9, 10, 11], [12]]]], 13, [14, 15], [16]],
f
]
cases.each_with_index do |c, i|
print "#{i}. "; print c; puts
d = c.dup
a = d.flatten
r = c.mattflat
print "r: "; print r; puts
print "a: "; print a; puts
puts (r == a) ? "pass" : "fail"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment