Class: Contracts::Builtin::Xor

Inherits:
CallableClass show all
Defined in:
lib/contracts-ruby2/lib/contracts/builtin_contracts.rb,
lib/contracts-ruby3/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.



120
121
122
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 120

def initialize(*vals)
  @vals = vals
end

Instance Method Details

#to_sObject



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

def to_s
  @vals[0, @vals.size-1].map do |x|
    InspectWrapper.create(x)
  end.join(", ") + " xor " + InspectWrapper.create(@vals[-1]).to_s
end

#valid?(val) ⇒ Boolean

Returns:

  • (Boolean)


124
125
126
127
128
129
130
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 124

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