Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'pp'
- a = ['one',['two','three'],[['four','five','six']], [[['seven','eight','nine','ten']]]]
- class Array
- alias_method :old_flatten, :flatten
- def flatten(depth=nil)
- if depth.nil?
- ret = old_flatten
- else
- if depth == 0
- ret = self
- else
- depth -= 1
- ret = []
- each do |x|
- if x.kind_of? Array
- ret += x.flatten(depth)
- else
- ret << x
- end
- end
- end
- end
- ret
- end
- end
- puts "flatten it one level"
- pp a.flatten(1)
- puts "flatten it to two"
- pp a.flatten(2)
- puts "flatten it to 100"
- pp a.flatten(100)
Add Comment
Please, Sign In to add comment