Sha256: 1fc44cf6c132c7154f02c8dce6facf64bf4de10bf44ba16449314a2ffa4325c6

Contents?: true

Size: 1.45 KB

Versions: 26

Compression:

Stored size: 1.45 KB

Contents

#--
# Credit goes to Gavin Sinclair.
#++
class Hash

  # Modifies the receiving Hash so that the value previously referred to by 
  # _oldkey_ is also referenced by _newkey_; _oldkey_ is retained in the Hash.
  # If _oldkey_ does not exist as a key in the Hash, no change is effected.
  #
  # Returns a reference to the Hash.
  #
  #   foo = { :name=>'Gavin', 'wife'=>:Lisa }
  #   foo.alias!('name',:name)     => { :name=>'Gavin', 'name'=>'Gavin', 'wife'=>:Lisa }
  #
  #   foo = { :name=>'Gavin', 'wife'=>:Lisa }
  #   foo.alias!('spouse','wife')  => { :name=>'Gavin', 'wife'=>:Lisa, 'spouse'=>:Lisa }
  #
  #   foo = { :name=>'Gavin', 'wife'=>:Lisa }
  #   foo.alias!('bar','foo')      => { :name=>'Gavin', 'wife'=>:Lisa }
  #
  # Note that if the _oldkey_ is reassigned, the reference will no longer exist,
  # and the _newkey_ will remain as it was.
  def alias!( newkey, oldkey )
    self[newkey] = self[oldkey] if self.has_key?(oldkey)
    self
  end

end


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

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

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

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

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