1
1
class Hash
2
2
# Return a new hash with all keys converted using the block operation.
3
3
#
4
- # { :name => 'Rob', :years => '28' }.transform_keys{ |key| key.to_s.upcase }
5
- # # => { "NAME" => "Rob", "YEARS" => "28" }
4
+ # hash = { name: 'Rob', age: '28' }
5
+ #
6
+ # hash.transform_keys{ |key| key.to_s.upcase }
7
+ # # => { "NAME" => "Rob", "AGE" => "28" }
6
8
def transform_keys
7
9
result = { }
8
10
keys . each do |key |
@@ -22,8 +24,10 @@ def transform_keys!
22
24
23
25
# Return a new hash with all keys converted to strings.
24
26
#
25
- # { :name => 'Rob', :years => '28' }.stringify_keys
26
- # #=> { "name" => "Rob", "years" => "28" }
27
+ # hash = { name: 'Rob', age: '28' }
28
+ #
29
+ # hash.stringify_keys
30
+ # #=> { "name" => "Rob", "age" => "28" }
27
31
def stringify_keys
28
32
transform_keys { |key | key . to_s }
29
33
end
@@ -37,8 +41,10 @@ def stringify_keys!
37
41
# Return a new hash with all keys converted to symbols, as long as
38
42
# they respond to +to_sym+.
39
43
#
40
- # { 'name' => 'Rob', 'years' => '28' }.symbolize_keys
41
- # #=> { :name => "Rob", :years => "28" }
44
+ # hash = { 'name' => 'Rob', 'age' => '28' }
45
+ #
46
+ # hash.symbolize_keys
47
+ # #=> { name: "Rob", age: "28" }
42
48
def symbolize_keys
43
49
transform_keys { |key | key . to_sym rescue key }
44
50
end
@@ -69,8 +75,10 @@ def assert_valid_keys(*valid_keys)
69
75
# This includes the keys from the root hash and from all
70
76
# nested hashes.
71
77
#
72
- # { :person => { :name => 'Rob', :years => '28' } }.deep_transform_keys{ |key| key.to_s.upcase }
73
- # # => { "PERSON" => { "NAME" => "Rob", "YEARS" => "28" } }
78
+ # hash = { person: { name: 'Rob', age: '28' } }
79
+ #
80
+ # hash.deep_transform_keys{ |key| key.to_s.upcase }
81
+ # # => { "PERSON" => { "NAME" => "Rob", "AGE" => "28" } }
74
82
def deep_transform_keys ( &block )
75
83
result = { }
76
84
each do |key , value |
0 commit comments