Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. class FlattenEnum
  2. class << self
  3.  
  4. # Returns an enumerator that yields the non-enumerable items from within a
  5. # nested enumerable, in depth-first order.
  6. #
  7. # Example:
  8. #
  9. # FlattenEnum.create([[1, 2, [3]], 4]).to_a
  10. # #=> [1, 2, 3, 4]
  11. def create(nested_collection)
  12. Enumerator.new do |yielder|
  13.  
  14. # The single-item case. Yield the item and stop the iteration.
  15. unless nested_collection.respond_to?(:each)
  16. item = nested_collection
  17. yielder << item
  18. raise StopIteration
  19. end
  20.  
  21. # Recurse over each of the collection's elements in case they need
  22. # flattening.
  23. nested_collection.each do |element|
  24. inner_enum = create(element)
  25. loop do
  26. yielder << inner_enum.next
  27. end
  28. end
  29.  
  30. end
  31. end
  32.  
  33. end
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement