Class: Enumerator::Filter

Inherits:
Enumerator show all
Defined in:
lib/enumerable_lz/filter.rb,
lib/enumerable_lz/filter_mrb.rb

Overview

Lazy Filterring Enumerator

Constant Summary collapse

TrueProc =
Proc.new{true}

Instance Method Summary collapse

Constructor Details

#initialize(obj, the_filter = nil) ⇒ Filter

Returns a new instance of Filter.

Parameters:

  • an Enumerable.

  • (defaults to: nil)

    filterring pattern or proc.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/enumerable_lz/filter.rb', line 9

def initialize obj, the_filter=nil
  @org_enum = obj
  super() do |y|
    compiled_filter = @filter.nil? ? Proc.new{true} : lambda{|f|
      break f[0] if f.size==1
      codes = f.size.times.map do |idx|
        "f[#{idx}]===el"
      end
      eval "Proc.new{|el|"+codes.join(" && ")+"}"
    }.call(@filter)
    catch :do_break do
      @org_enum.each do |el|
        y.yield el if compiled_filter===el
      end
    end
  end
  filter! the_filter if the_filter
end

Instance Method Details

#filter(pattern = nil, &block) ⇒ Object

override


49
50
51
52
53
54
55
56
57
58
# File 'lib/enumerable_lz/filter.rb', line 49

def filter pattern=nil, &block
  # clone.filter! pattern, &block
  patterns = @filter.nil? ? [] : @filter.clone
  if pattern.is_a? Array
    patterns.push(*pattern)
  else
    patterns<<(pattern || block)
  end
  Filter.new @org_enum, patterns
end

#filter!(pattern = nil) {|el| ... } ⇒ Filter

Apply filter pattern/block and return self. (bang method of filter)

Yields:

  • (el)

Returns:

  • self



31
32
33
34
35
36
37
38
39
# File 'lib/enumerable_lz/filter.rb', line 31

def filter! pattern=nil, &block
  @filter||=[]
  if pattern.is_a? Array
    pattern.each{|el| @filter << conv_proc(el)}
  else
    @filter << conv_proc(pattern || block)
  end
  self
end

#with_index(offset = 0, &block) ⇒ Object

override

Raises:



79
80
81
82
83
84
85
# File 'lib/enumerable_lz/filter.rb', line 79

def with_index offset=0, &block
  raise ArgumentError, "tried to call filter.with_index without a block" unless block_given?
  i = offset - 1
  with_initializer(Proc.new{i = offset - 1}) do |el|
    block.call(el, i += 1)
  end
end

#with_initializer(init_proc) { ... } ⇒ Filter #with_initializer(init_proc, pattern) ⇒ Filter

Overloads:

  • #with_initializer(init_proc) { ... } ⇒ Filter

    filter by block with initializer proc.

    Parameters:

    • initializer proc. (uses .call method)

    Yields:

    • filterring block.

    Returns:

  • #with_initializer(init_proc, pattern) ⇒ Filter

    filter by pattern with initializer proc.

    Parameters:

    • initializer proc. (uses .call method)

    • filterring pattern. (uses === method)

    Returns:

Returns:



71
72
73
74
# File 'lib/enumerable_lz/filter.rb', line 71

def with_initializer init_proc, pattern = nil, &block
  src_enum = @filter.nil? ? @org_enum : self
  FilterWithInitializer.new src_enum, init_proc, pattern||block
end