Class: Matchi::Eq

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

Overview

Value equivalence matcher that checks if two objects have identical values.

This matcher verifies value equality using Ruby’s Object#eql? method, which compares the values of objects rather than their identity. This is different from identity comparison (equal?) which checks if objects are the same instance.

Examples:

Basic usage with strings

matcher = Matchi::Eq.new("test")
matcher.match? { "test" }         # => true
matcher.match? { "test".dup }     # => true
matcher.match? { "other" }        # => false

With numbers

matcher = Matchi::Eq.new(42)
matcher.match? { 42 }             # => true
matcher.match? { 42.0 }           # => false  # Different types
matcher.match? { 43 }             # => false

With collections

array = [1, 2, 3]
matcher = Matchi::Eq.new(array)
matcher.match? { array.dup }      # => true   # Same values
matcher.match? { array }          # => true   # Same object
matcher.match? { [1, 2, 3] }      # => true   # Same values
matcher.match? { [1, 2] }         # => false  # Different values

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ Eq

Initialize the matcher with a reference value.

Examples:

Eq.new("test")              # Match strings with same value
Eq.new([1, 2, 3])           # Match arrays with same elements

Parameters:

  • expected (#eql?)

    The expected equivalent value



44
45
46
# File 'lib/matchi/eq.rb', line 44

def initialize(expected)
  @expected = expected
end

Instance Method Details

#match? { ... } ⇒ Boolean

Checks if the yielded object has a value equivalent to the expected object.

This method uses Ruby’s Object#eql? method, which performs value comparison. Two objects are considered equivalent if they have the same value, even if they are different instances.

Examples:

matcher = Eq.new([1, 2, 3])
matcher.match? { [1, 2, 3] }      # => true
matcher.match? { [1, 2, 3].dup }  # => true

Yields:

  • Block that returns the object to check

Yield Returns:

  • (Object)

    The object to verify equivalence with

Returns:

  • (Boolean)

    true if both objects have equivalent values

Raises:

  • (ArgumentError)

    if no block is provided



67
68
69
70
71
# File 'lib/matchi/eq.rb', line 67

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

  @expected.eql?(yield)
end

#to_sString

Returns a human-readable description of the matcher.

Examples:

Eq.new("test").to_s # => 'eq "test"'

Returns:

  • (String)

    A string describing what this matcher verifies



81
82
83
# File 'lib/matchi/eq.rb', line 81

def to_s
  "eq #{@expected.inspect}"
end