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