Sha256: 5a25576965023b3d2fb966165aa73625ed1c92e17cb69f9aed522eb7a6a0b2bd

Contents?: true

Size: 1.27 KB

Versions: 10

Compression:

Stored size: 1.27 KB

Contents

# TITLE:
#
#   Hash Comparison Extensions
#
# SUMMARY:
#
#   Hash comparison extensions.
#
# CREDITS:
#
#   - Thomas Sawyer
#

class Hash

  # Returns true or false whether the hash
  # contains the given keys.
  #
  #   h = { :a => 1, :b => 2 }
  #   h.has_keys?( :a )   #=> true
  #   h.has_keys?( :c )   #=> false

  def has_keys?(*check_keys)
    unknown_keys = check_keys - self.keys
    return unknown_keys.empty?
  end

  # Returns true if the hash contains
  # _only_ the given keys, otherwise false.
  #
  #   h = { :a => 1, :b => 2 }
  #   h.has_only_keys?( :a, :b )   #=> true
  #   h.has_only_keys?( :a )       #=> false

  def has_only_keys?(*check_keys)
    unknown_keys = self.keys - check_keys
    return unknown_keys.empty?
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TestHashHasKeys < Test::Unit::TestCase

    # TODO Write test for Hash#diff.

    def test_has_keys?
      assert( { :a=>1,:b=>2,:c=>3 }.has_keys?(:a,:b) )
      assert( ! { :a=>1,:b=>2,:c=>3 }.has_keys?(:a,:b,:d) )
    end

    def test_has_only_keys?
      assert( { :a=>1,:b=>2,:c=>3 }.has_only_keys?(:a,:b,:c) )
      assert( ! { :a=>1,:b=>2,:c=>3 }.has_only_keys?(:a,:b) )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.0 lib/core/facets/hash/has_keys.rb
facets-2.0.1 lib/core/facets/hash/has_keys.rb
facets-2.0.2 lib/core/facets/hash/has_keys.rb
facets-2.1.0 lib/core/facets/hash/has_keys.rb
facets-2.1.1 lib/core/facets/hash/has_keys.rb
facets-2.1.2 lib/core/facets/hash/has_keys.rb
facets-2.0.3 lib/core/facets/hash/has_keys.rb
facets-2.0.4 lib/core/facets/hash/has_keys.rb
facets-2.0.5 lib/core/facets/hash/has_keys.rb
facets-2.1.3 lib/core/facets/hash/has_keys.rb