mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #24517 from estolfo/transform-keys-return-type-master
Restore Hash#transform_keys behavior to always return a Hash instance
This commit is contained in:
commit
b0d7ac0ff7
2 changed files with 17 additions and 1 deletions
|
@ -11,7 +11,7 @@ class Hash
|
|||
# hash.transform_keys.with_index { |k, i| [k, i].join } # => {"name0"=>"Rob", "age1"=>"28"}
|
||||
def transform_keys
|
||||
return enum_for(:transform_keys) { size } unless block_given?
|
||||
result = self.class.new
|
||||
result = {}
|
||||
each_key do |key|
|
||||
result[yield(key)] = self[key]
|
||||
end
|
||||
|
|
|
@ -43,4 +43,20 @@ class TransformKeysTest < ActiveSupport::TestCase
|
|||
original.transform_keys!.with_index { |k, i| [k, i].join.to_sym }
|
||||
assert_equal({ a0: 'a', b1: 'b' }, original)
|
||||
end
|
||||
|
||||
test "transform_keys returns a Hash instance when self is inherited from Hash" do
|
||||
class HashDescendant < ::Hash
|
||||
def initialize(elements = nil)
|
||||
super(elements)
|
||||
(elements || {}).each_pair{ |key, value| self[key] = value }
|
||||
end
|
||||
end
|
||||
|
||||
original = HashDescendant.new({ a: 'a', b: 'b' })
|
||||
mapped = original.transform_keys { |k| "#{k}!".to_sym }
|
||||
|
||||
assert_equal({ a: 'a', b: 'b' }, original)
|
||||
assert_equal({ a!: 'a', b!: 'b' }, mapped)
|
||||
assert_equal(::Hash, mapped.class)
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue