Class: Contracts::Builtin::Xor

Inherits:
CallableClass show all
Defined in:
lib/contracts/builtin_contracts.rb

Overview

Takes a variable number of contracts. The contract passes if exactly one of those contracts pass. Example: Xor[Fixnum, Float]

Instance Method Summary collapse

Methods inherited from CallableClass

[]

Constructor Details

#initialize(*vals) ⇒ Xor

Returns a new instance of Xor.


125
126
127
128
# File 'lib/contracts/builtin_contracts.rb', line 125

def initialize(*vals)
  super()
  @vals = vals
end

Instance Method Details

#to_sObject


138
139
140
141
142
143
144
# File 'lib/contracts/builtin_contracts.rb', line 138

def to_s
  # rubocop:disable Style/StringConcatenation
  @vals[0, @vals.size-1].map do |x|
    InspectWrapper.create(x)
  end.join(", ") + " xor " + InspectWrapper.create(@vals[-1]).to_s
  # rubocop:enable Style/StringConcatenation
end

#valid?(val) ⇒ Boolean

Returns:

  • (Boolean)

130
131
132
133
134
135
136
# File 'lib/contracts/builtin_contracts.rb', line 130

def valid?(val)
  results = @vals.map do |contract|
    res, _ = Contract.valid?(val, contract)
    res
  end
  results.count(true) == 1
end