Skip to content

Commit c5949ab

Browse files
authored
Merge pull request rails#50648 from byroot/opt-stringify-keys
Optimize Hash#stringify_keys
2 parents 0b04c15 + 8c7e69b commit c5949ab

File tree

3 files changed

+12
-6
lines changed

3 files changed

+12
-6
lines changed

activesupport/lib/active_support/core_ext/hash/keys.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@ class Hash
88
# hash.stringify_keys
99
# # => {"name"=>"Rob", "age"=>"28"}
1010
def stringify_keys
11-
transform_keys(&:to_s)
11+
transform_keys { |k| Symbol === k ? k.name : k.to_s }
1212
end
1313

1414
# Destructively converts all keys to strings. Same as
1515
# +stringify_keys+, but modifies +self+.
1616
def stringify_keys!
17-
transform_keys!(&:to_s)
17+
transform_keys! { |k| Symbol === k ? k.name : k.to_s }
1818
end
1919

2020
# Returns a new hash with all keys converted to symbols, as long as
@@ -82,14 +82,14 @@ def deep_transform_keys!(&block)
8282
# hash.deep_stringify_keys
8383
# # => {"person"=>{"name"=>"Rob", "age"=>"28"}}
8484
def deep_stringify_keys
85-
deep_transform_keys(&:to_s)
85+
deep_transform_keys { |k| Symbol === k ? k.name : k.to_s }
8686
end
8787

8888
# Destructively converts all keys to strings.
8989
# This includes the keys from the root hash and from all
9090
# nested hashes and arrays.
9191
def deep_stringify_keys!
92-
deep_transform_keys!(&:to_s)
92+
deep_transform_keys! { |k| Symbol === k ? k.name : k.to_s }
9393
end
9494

9595
# Returns a new hash with all keys converted to symbols, as long as

activesupport/lib/active_support/hash_with_indifferent_access.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ def to_proc
393393

394394
private
395395
def convert_key(key)
396-
key.kind_of?(Symbol) ? key.name : key
396+
Symbol === key ? key.name : key
397397
end
398398

399399
def convert_value(value, conversion: nil)

activesupport/lib/active_support/json/encoding.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,13 @@ def jsonify(value)
7676
when Hash
7777
result = {}
7878
value.each do |k, v|
79-
k = k.to_s unless String === k
79+
unless String === k
80+
k = if Symbol === k
81+
k.name
82+
else
83+
k.to_s
84+
end
85+
end
8086
result[k] = jsonify(v)
8187
end
8288
result

0 commit comments

Comments
 (0)