Sha256: 0d1939be19c386d0491beea2819e439f0e4791ed3aae6e37f197ed4e2e982639
Contents?: true
Size: 1.51 KB
Versions: 10
Compression:
Stored size: 1.51 KB
Contents
class Hash # Converts all keys in the Hash accroding to the given block. # If the block return +nil+ for given key, then that key will be # left intact. # # foo = { :name=>'Gavin', :wife=>:Lisa } # foo.normalize_keys{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa } # foo.inspect #=> { :name =>"Gavin", :wife=>:Lisa } # #-- # Adapted from Gavin Sinclair's #convert_keys. #++ def normalize_keys( &block ) dup.send(:normalize_keys!, &block) end # Synonym for Hash#normalize_keys, but modifies the receiver in place (and returns it). # # foo = { :name=>'Gavin', :wife=>:Lisa } # foo.normalize_keys!{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa } # foo.inspect #=> { "name"=>"Gavin", "wife"=>:Lisa } # #-- # Adapted from Gavin Sinclair's #convert_keys. #++ def normalize_keys!( &block ) keys.each{ |k| nk = block[k] self[nk]=delete(k) if nk } self end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TestHash < Test::Unit::TestCase def test_01 foo = { :a=>1, :b=>2 } assert_equal( { "a"=>1, "b"=>2 }, foo.normalize_keys{|k|k.to_s} ) assert_equal( { :a =>1, :b=>2 }, foo ) end def test_02 foo = { :a=>1, :b=>2 } assert_equal( { "a"=>1, "b"=>2 }, foo.normalize_keys!{|k|k.to_s} ) assert_equal( { "a"=>1, "b"=>2 }, foo ) end end =end
Version data entries
10 entries across 10 versions & 1 rubygems