Class: Qo::Matchers::ArrayMatcher

Inherits:
BaseMatcher show all
Defined in:
lib/qo/matchers/array_matcher.rb

Overview

An Array Matcher is a matcher that uses only *varargs to define a sequence of matches to perform against either an object or another Array.

In the case of an Array matching against an Array it will compare via index.

# Shorthand
Qo[1..10, 1..10].call([1, 2])
# => true

Qo::Matchers::ArrayMatcher.new([1..10, 1..10]).call([1, 2])
# => true

In the case of an Array matching against an Object, it will match each provided matcher against the object.

# Shorthand
Qo[Integer, 1..10].call(1)
# => true

Qo::Matchers::ArrayMatcher.new([1..10, 1..10]).call(1)
# => true

All variants present in the BaseMatcher are present here, including 'and', 'not', and 'or'.

Author:

  • baweaver

Since:

  • 0.2.0

Instance Method Summary collapse

Methods inherited from BaseMatcher

#initialize

Constructor Details

This class inherits a constructor from Qo::Matchers::BaseMatcher

Instance Method Details

#call(target) ⇒ Boolean

Runs the matcher directly.

If the target is an Array, it will be matched via index

If the target is an Object, it will be matched via public send

Parameters:

  • target (Any)

    Target to match against

Returns:

  • (Boolean)

    Result of the match

Since:

  • 0.2.0



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/qo/matchers/array_matcher.rb', line 58

def call(target)
  return true if @array_matchers == target

  if target.is_a?(::Array)
    match_with(@array_matchers.each_with_index) { |matcher, i|
      match_value?(target[i], matcher)
    }
  else
    match_with(@array_matchers) { |matcher|
      match_value?(target, matcher)
    }
  end
end

#to_procProc[Any]

Wrapper around call to allow for invocation in an Enumerable function, such as:

people.select(&Qo[/Foo/, 20..40])

Returns:

  • (Proc[Any])

    Proc awaiting a target to match against

Since:

  • 0.2.0



45
46
47
# File 'lib/qo/matchers/array_matcher.rb', line 45

def to_proc
  Proc.new { |target| self.call(target) }
end