Class: Matchi::BeWithin::Of

Inherits:
Object
  • Object
show all
Defined in:
lib/matchi/be_within.rb

Overview

Nested class that performs the actual comparison.

This class implements the actual matching logic, comparing the provided value against the expected value using the specified delta.

Instance Method Summary collapse

Constructor Details

#initialize(delta, expected) ⇒ Of

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize the matcher with a delta and an expected value.

Parameters:

  • delta (Numeric)

    The maximum allowed difference from the expected value

  • expected (Numeric)

    The reference value to compare against

Raises:

  • (ArgumentError)

    if delta is not a Numeric

  • (ArgumentError)

    if expected is not a Numeric

  • (ArgumentError)

    if delta is negative



103
104
105
106
107
108
109
110
# File 'lib/matchi/be_within.rb', line 103

def initialize(delta, expected)
  raise ::ArgumentError, "delta must be a Numeric" unless delta.is_a?(::Numeric)
  raise ::ArgumentError, "expected must be a Numeric" unless expected.is_a?(::Numeric)
  raise ::ArgumentError, "delta must be non-negative" if delta.negative?

  @delta = delta
  @expected = expected
end

Instance Method Details

#match? { ... } ⇒ Boolean

Checks if the yielded value is within the accepted range.

The value is considered within range if its absolute difference from the expected value is less than or equal to the specified delta.

Examples:

matcher = BeWithin.new(0.5).of(3.14)
matcher.match? { 3.0 }   # => true
matcher.match? { 4.0 }   # => false

Yields:

  • Block that returns the value to check

Yield Returns:

  • (Numeric)

    The value to verify

Returns:

  • (Boolean)

    true if the value is within the accepted range

Raises:

  • (ArgumentError)

    if no block is provided



130
131
132
133
134
# File 'lib/matchi/be_within.rb', line 130

def match?
  raise ::ArgumentError, "a block must be provided" unless block_given?

  (@expected - yield).abs <= @delta
end

#to_sString

Returns a human-readable description of the matcher.

Examples:

BeWithin.new(0.5).of(3.14).to_s # => "be within 0.5 of 3.14"

Returns:

  • (String)

    A string describing what this matcher verifies



144
145
146
# File 'lib/matchi/be_within.rb', line 144

def to_s
  "be within #{@delta} of #{@expected}"
end