Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class FlattenEnum
- class << self
- # Returns an enumerator that yields the non-enumerable items from within a
- # nested enumerable, in depth-first order.
- #
- # Example:
- #
- # FlattenEnum.create([[1, 2, [3]], 4]).to_a
- # #=> [1, 2, 3, 4]
- def create(nested_collection)
- Enumerator.new do |yielder|
- # The single-item case. Yield the item and stop the iteration.
- unless nested_collection.respond_to?(:each)
- item = nested_collection
- yielder << item
- raise StopIteration
- end
- # Recurse over each of the collection's elements in case they need
- # flattening.
- nested_collection.each do |element|
- inner_enum = create(element)
- loop do
- yielder << inner_enum.next
- end
- end
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement