Class: Contracts::Builtin::HashOf

Inherits:
CallableClass show all
Defined in:
lib/contracts-ruby2/lib/contracts/builtin_contracts.rb,
lib/contracts-ruby3/lib/contracts/builtin_contracts.rb

Overview

Use this to specify the Hash characteristics. Takes two contracts, one for hash keys and one for hash values. Example: HashOf[Symbol, String]

Constant Summary collapse

INVALID_KEY_VALUE_PAIR =
"You should provide only one key-value pair to HashOf contract"

Instance Method Summary collapse

Methods inherited from CallableClass

[]

Constructor Details

#initialize(key, value = nil) ⇒ HashOf

Returns a new instance of HashOf.



366
367
368
369
370
371
372
373
374
375
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 366

def initialize(key, value = nil)
  if value
    @key   = key
    @value = value
  else
    validate_hash(key)
    @key   = key.keys.first
    @value = key[@key]
  end
end

Instance Method Details

#to_sObject



385
386
387
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 385

def to_s
  "Hash<#{@key}, #{@value}>"
end

#valid?(hash) ⇒ Boolean

Returns:

  • (Boolean)


377
378
379
380
381
382
383
# File 'lib/contracts-ruby2/lib/contracts/builtin_contracts.rb', line 377

def valid?(hash)
  return false unless hash.is_a?(Hash)
  keys_match = hash.keys.map { |k| Contract.valid?(k, @key) }.all?
  vals_match = hash.values.map { |v| Contract.valid?(v, @value) }.all?

  [keys_match, vals_match].all?
end