Sha256: b8f0d76d1acf01362040d309b7d639b8ad7797ead96702644a587bebe5021862

Contents?: true

Size: 1.07 KB

Versions: 26

Compression:

Stored size: 1.07 KB

Contents

class Hash
  # Modifies the receiving Hash so that the value previously referred to by
  # _oldkey_ is referenced by _newkey_; _oldkey_ is removed from the Hash.
  # If _oldkey_ does not exist as a key in the Hash, no change is effected.
  #
  # Returns a reference to the Hash.
  #
  #   foo = { :a=>1, :b=>2 }
  #   foo.swapkey!('a',:a)       #=> { 'a'=>1, :b=>2 }
  #   foo.swapkey!('b',:b)       #=> { 'a'=>1, 'b'=>2 }
  #   foo.swapkey!('foo','bar')  #=> { 'a'=>1, 'b'=>2 }
  #
  #--
  # Credit goes to Gavin Sinclair.
  #++
  def swapkey!( newkey, oldkey )
    self[newkey] = self.delete(oldkey) if self.has_key?(oldkey)
    self
  end
end


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

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_swapkeys!
      foo = { :a=>1, :b=>2 }
      assert_equal( { 'a'=>1, :b=>2 }, foo.swapkey!('a', :a) )
      assert_equal( { 'a'=>1, 'b'=>2 }, foo.swapkey!('b', :b) )
      assert_equal( { 'a'=>1, 'b'=>2 }, foo.swapkey!('foo','bar') )
    end

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-1.0.3 packages/core/lib/facet/hash/swapkey.rb
facets-0.9.0 lib/nano/hash/swapkey.rb
facets-1.0.0 lib/facet/hash/swapkey.rb
facets-1.2.1 lib/facets/core/hash/swapkey.rb
facets-1.3.0 lib/facets/core/hash/swapkey.rb
facets-1.1.0 lib/facet/hash/swapkey.rb
facets-1.2.0 lib/facets/core/hash/swapkey.rb
facets-1.3.2 lib/facets/core/hash/swapkey.rb
facets-1.3.3 lib/facets/core/hash/swapkey.rb
facets-1.3.1 lib/facets/core/hash/swapkey.rb
facets-1.4.0 lib/facets/core/hash/swapkey.rb
facets-1.4.2 lib/facets/core/hash/swapkey.rb
facets-1.4.1 lib/facets/core/hash/swapkey.rb
facets-1.4.3 lib/facets/core/hash/swapkey.rb
facets-1.4.5 lib/facets/core/hash/swapkey.rb
facets-1.4.4 lib/facets/core/hash/swapkey.rb
facets-1.7.30 lib/facets/core/hash/swapkey.rb
facets-1.7.38 lib/facets/core/hash/swapkey.rb
facets-1.7.0 lib/facets/core/hash/swapkey.rb
facets-1.7.46 lib/facets/core/hash/swapkey.rb