Class: Enumerable::Recursor

Inherits:
Object show all
Defined in:
lib/core/facets/enumerable/recursively.rb

Overview

Recursor is a specialized Functor for recurively iterating over Enumerables.

TODO: Return Enumerator if no yld block is given.

TODO: Add limiting depth option to Enumerable#recursively?

Direct Known Subclasses

Hash::Recursor

Instance Method Summary collapse

Constructor Details

#initialize(enum, *types, &block) ⇒ Recursor

Returns a new instance of Recursor.



20
21
22
23
24
# File 'lib/core/facets/enumerable/recursively.rb', line 20

def initialize(enum, *types, &block)
  @enum   = enum
  @types  = types.empty? ? [@enum.class] : types
  @block  = block
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(op, &yld) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/core/facets/enumerable/recursively.rb', line 26

def method_missing(op, &yld)
  rec = @block || lambda{ |v| v }
  yld = yld    || lambda{ |v| v }  # ? to_enum
  @enum.__send__(op) do |v|
    case v
    when String # b/c of 1.8
      yld.call(v)
    when *@types
      res = v.recursively(*@types, &@block).__send__(op,&yld)
      rec.call(res)
    else
      yld.call(v)
    end
  end
end