Skip to content

Commit f4725c2

Browse files
committed
Allow Hash#transform_keys to take a hash argument
1 parent e9f7e06 commit f4725c2

File tree

1 file changed

+23
-6
lines changed
  • src/main/ruby/truffleruby/core

1 file changed

+23
-6
lines changed

src/main/ruby/truffleruby/core/hash.rb

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -539,25 +539,42 @@ def transform_values!
539539
self
540540
end
541541

542-
def transform_keys
543-
return to_enum(:transform_keys) { size } unless block_given?
542+
def transform_keys(mapping = nil)
543+
has_block = block_given?
544+
return to_enum(:transform_keys) { size } unless mapping || has_block
545+
546+
mapping = Truffle::Type.coerce_to(mapping, Hash, :to_hash) if mapping
544547

545548
h = {}
546549
each_pair do |key, value|
547-
h[yield(key)] = value
550+
if mapping
551+
k = Primitive.hash_get_or_undefined(mapping, key)
552+
k = has_block ? yield(key) : key if Primitive.undefined?(k)
553+
h[k] = value
554+
else
555+
h[yield(key)] = value
556+
end
548557
end
549558
h
550559
end
551560

552-
def transform_keys!
553-
return to_enum(:transform_keys!) { size } unless block_given?
561+
def transform_keys!(mapping = nil)
562+
has_block = block_given?
563+
return to_enum(:transform_keys!) { size } unless mapping || has_block
554564

555565
Primitive.check_frozen self
566+
mapping = Truffle::Type.coerce_to(mapping, Hash, :to_hash) if mapping
556567

557568
h = {}
558569
begin
559570
each_pair do |key, value|
560-
h[yield(key)] = value
571+
if mapping
572+
k = Primitive.hash_get_or_undefined(mapping, key)
573+
k = has_block ? yield(key) : key if Primitive.undefined?(k)
574+
h[k] = value
575+
else
576+
h[yield(key)] = value
577+
end
561578
end
562579
ensure
563580
replace h

0 commit comments

Comments
 (0)