Class: TrickBag::Enumerables::FilteredEnumerable

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/trick_bag/enumerables/filtered_enumerable.rb

Overview

Decorator that wraps an Enumerable and takes a filter predicate to determine whether or not objects from the wrapped enumerator should be processed.

The filter is an optional parameter on the constructor, but can also be set after creation with a mutator.

If you do not intend to change the filter after it is created, you should probably just use Ruby’s built in lazy enumerators, as in: e = (1..10000000000000000000000000000).lazy.select { |n| n.even? }.lazy

This class really comes in handy when the filter needs to be changed during the enumerator’s lifetime.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(wrapped_enumerator, filter = ->(_) { true }) ⇒ FilteredEnumerable

Returns a new instance of FilteredEnumerable.

Parameters:

  • wrapped_enumerator

    the enumerator to filter

  • filter (defaults to: ->(_) { true })

    a lambda that returns whether or not to yield a given object, defaults to lambda always returning true



29
30
31
32
# File 'lib/trick_bag/enumerables/filtered_enumerable.rb', line 29

def initialize(wrapped_enumerator, filter = ->(_) { true })
  @wrapped_enumerator = wrapped_enumerator
  @filter = filter
end

Instance Attribute Details

#filterObject

Returns the value of attribute filter.



24
25
26
# File 'lib/trick_bag/enumerables/filtered_enumerable.rb', line 24

def filter
  @filter
end

#wrapped_enumeratorObject (readonly)

Returns the value of attribute wrapped_enumerator.



23
24
25
# File 'lib/trick_bag/enumerables/filtered_enumerable.rb', line 23

def wrapped_enumerator
  @wrapped_enumerator
end

Instance Method Details

#eachObject

Standard Enumerable.each; returns an Enumerator if called without a block



35
36
37
38
39
40
41
# File 'lib/trick_bag/enumerables/filtered_enumerable.rb', line 35

def each
  return to_enum unless block_given?

  wrapped_enumerator.each do |thing|
    yield thing if filter.(thing)
  end
end