Module: Enumerable

Defined in:
lib/filter.rb

Overview

Synopsys

Extension for Ruby Enumerable module

Description

Extends Enumerable module with filter method - enhanced version of Enumerable#select.

Examples

[1, 2, 3, 'ab'].filter(/a/)               # => ['ab']
[1, 2, 3].filter(&:even?)                 # => [2]
[1, 2, 3, 4.2].filter :to_i => :even?     # => [2, 4]
[1, 2, 4].filter { |num| num.even? }      # => [2, 4]
[1, 2, 4].filter(:even?) { |n| n + 1 }    # => [3, 5]
[0, false, 2, nil].filter(true)           # => [0, 2]

Enumerable#filter also supports OR operator! Just pass many patterns as arguments. This snippet will match elements responding to zero? or odd? methods with true.

[0, 2, 3, 4].filter(:zero?, :odd?)        # => [0, 3]

Instance Method Summary collapse

Instance Method Details

#filter(*patterns, &block) ⇒ Enumerable

Extended Enumerable#select combibed with Enumerable#collect

When String or Regexp passed it acts as built-in Enumerable#grep method Also you can pass Symbol, Proc, Method, Array, Hash, Class, Module, true, false, nil. If the block is supplied without other arguments it will be used as filter. If the block is supplied with patterns, each matching element is passed to it, and the block’s result is stored in the output array.

Parameters:

  • patterns

    *[Numeric|String|Regexp|Symbol|Proc|Method|NilClass|Hash|TrueClass|FalseClass|Module|Class]

  • block (Proc)

Returns:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/filter.rb', line 34

def filter(*patterns, &block) # :yields: obj
  # do nothing on null input
  return self if !block_given? && patterns.empty?

  # move +block+ to +patterns+ if no +patterns+ given
  patterns, block = [block], nil if block_given? && patterns.empty?
  # match elements against all patterns using +OR+ operator
  conditions = Filter.or(*patterns)

  filtered = select { |obj| conditions === obj }

  # also transform elements if block given
  block ? filtered.map(&block) : filtered
end