Sha256: 57616fd480b69f7fd30728ee5594284593fd1bf40be8aeb541599222b368f297

Contents?: true

Size: 1.73 KB

Versions: 10

Compression:

Stored size: 1.73 KB

Contents

# TITLE:
#
#   Hash Deletion Extensions
#
# SUMMARY:
#
#   General manipulation extensions for Hash class.
#
# CREDITS:
#
#   - Daniel Schierbeck
#   - Thomas Sawyer

#
class Hash

  alias_method :delete_at, :delete

  # CREDIT Daniel Schierbeck

  def delete_unless #:yield:
    delete_if{ |key, value| ! yield(key, value) }
  end

  # CREDIT Daniel Schierbeck

  # Minor modification to Ruby's Hash#delete method
  # allowing it to take multiple keys.
  #
  #   hsh = { :a => 1, :b => 2 }
  #   hsh.delete_values(1)
  #   hsh  #=> { :b => 2 }

  def delete_values(*values)
    keys.map{ |key| delete(key) if values.include?(fetch(key)) }
  end

  # CREDIT Daniel Schierbeck

  # Minor modification to Ruby's Hash#delete method
  # allowing it to take multiple keys.
  #
  # This works niely with hash#[] and Hash#[]= facets.
  #
  #    hsh[:a, :b, :c] = 1, 2, 3
  #
  #    a, b, c = hsh.delete_values_at(:a, :b, :c)
  #
  #    [a, b, c]  #=> [1, 2, 3]
  #    hsh        #=> {}

  def delete_values_at(*keys, &yld)
    keys.map{|key| delete(key, &yld) }
  end

end



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

  require 'test/unit'

  class TestHashDelete < Test::Unit::TestCase

    def test_delete_unless
      a = { :a => 1, :b => 2, :c => 3 }
      e = { :a => 1 }
      r = a.delete_unless{|k,v| v == 1}
      assert_equal( e, a )
    end

    def test_delete_values
      a = { :a => 1, :b => 2, :c => 3 }
      e = { :b => 2, :c => 3 }
      r = a.delete_values(1)
      assert_equal( e, a )
    end

    def test_delete_values_at
      a = { :a => 1, :b => 2, :c => 3 }
      e = { :b => 2, :c => 3 }
      r = a.delete_values_at(:a)
      assert_equal( e, a )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

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