Class: Jinx::Filter

Inherits:
Object show all
Includes:
Collection
Defined in:
lib/jinx/helpers/filter.rb

Overview

This Filter helper class applies a selection block to a base enumeration.

Instance Method Summary collapse

Methods included from Enumerable

#collection?, #compact, #compact_map, #detect_value, #detect_with_value, #difference, #empty?, #enumerate, #filter, #first, #flatten, #hashify, #intersect, #join, #last, #partial_sort, #partial_sort_by, #pp_s, #pretty_print, #pretty_print_cycle, #qp, #size, #to_compact_hash, #to_compact_hash_with_index, #to_enum, #to_series, #transform, #transitive_closure, #union

Constructor Details

#initialize(enum = [], &filter) ⇒ Filter

Returns a new instance of Filter.



6
7
8
9
# File 'lib/jinx/helpers/filter.rb', line 6

def initialize(enum=[], &filter)
  @base = enum
  @filter = filter
end

Instance Method Details

#<<(item) ⇒ Filter

Adds an item to the base Enumerable, if this Filter’s base supports it.

Parameters:

  • item

    the item to add

Returns:



32
33
34
35
# File 'lib/jinx/helpers/filter.rb', line 32

def <<(item)
  @base << item
  self
end

#each {|item| ... } ⇒ Object

Calls the given block on each item which passes this Filter’s filter test.

Yields:

  • (item)

    the block called on each item

Yield Parameters:

  • item

    the enumerated item



15
16
17
# File 'lib/jinx/helpers/filter.rb', line 15

def each
  @base.each { |item| yield(item) if @filter ? @filter.call(item) : item }
end

#include?(item) ⇒ Boolean

Optimized for a Set base.

Parameters:

  • the (item)

    item to check

Returns:

  • (Boolean)

    whether the item is a member of this Enumerable



23
24
25
26
# File 'lib/jinx/helpers/filter.rb', line 23

def include?(item)
  return false if Set === @base and not @base.include?(item)
  super
end

#merge(other) ⇒ Array

Returns this Filter’s filtered content merged with the other Enumerable.

Parameters:

Returns:

  • (Array)

    this Filter’s filtered content merged with the other Enumerable



39
40
41
# File 'lib/jinx/helpers/filter.rb', line 39

def merge(other)
  to_a.merge!(other)
end

#merge!(other) ⇒ Filter?

Merges the other Enumerable into the base Enumerable, if the base supports it.

Parameters:

Returns:

  • (Filter, nil)

    this Filter’s filtered content merged with the other Enumerable



47
48
49
50
# File 'lib/jinx/helpers/filter.rb', line 47

def merge!(other)
  @base.merge!(other)
  self
end