Class: Jinx::Filter

Inherits:
Object show all
Includes:
Enumerable, 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

#enumerate, #pp_s, #pretty_print, #pretty_print_cycle, #qp, #to_enum, #transitive_closure

Methods included from Collection

#compact, #compact_map, #detect_value, #detect_with_value, #difference, #empty?, #filter, #first, #flatten, #hashify, #intersect, #join, #last, #partial_sort, #partial_sort!, #partial_sort_by, #size, #to_compact_hash, #to_compact_hash_with_index, #to_series, #transform, #union

Constructor Details

#initialize(enum = []) {|item| ... } ⇒ Filter

Initializes this Filter’s from the given base enumeration and optional filter test. The default filter test is whether the item is non-nil and not false.

Parameters:

  • enum (Enumerable) (defaults to: [])

    the base enumeration to filter

Yields:

  • (item)

    the block called on each item

Yield Parameters:

  • item

    the enumerated item



12
13
14
15
# File 'lib/jinx/helpers/filter.rb', line 12

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:



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

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 filtered item

Yield Parameters:

  • item

    the enumerated item



21
22
23
# File 'lib/jinx/helpers/filter.rb', line 21

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



29
30
31
32
# File 'lib/jinx/helpers/filter.rb', line 29

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



45
46
47
# File 'lib/jinx/helpers/filter.rb', line 45

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



53
54
55
56
# File 'lib/jinx/helpers/filter.rb', line 53

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