From 8558d5e4801b74b058dc2a534be2be85037cadb5 Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Tue, 15 Dec 2020 17:05:35 -0500 Subject: Document Hash#transform_keys with hash. Amend NEWS [DOC] [ci skip] --- NEWS.md | 4 ++-- hash.c | 29 +++++++++++++++-------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/NEWS.md b/NEWS.md index 817d591a27..1bce4d8f73 100644 --- a/NEWS.md +++ b/NEWS.md @@ -196,8 +196,8 @@ Outstanding ones only. * Hash - * Hash#transform_keys now accepts a hash that maps keys to new - keys. [[Feature #16274]] + * Hash#transform_keys and transform_keys! now accepts a hash that maps + keys to new keys. [[Feature #16274]] * Hash#except has been added, which returns a hash excluding the given keys and their values. [[Feature #15822]] diff --git a/hash.c b/hash.c index 98405ec541..2f53c24647 100644 --- a/hash.c +++ b/hash.c @@ -3188,17 +3188,28 @@ transform_keys_i(VALUE key, VALUE value, VALUE result) * call-seq: * hash.transform_keys {|key| ... } -> new_hash * hash.transform_keys(hash2) -> new_hash + * hash.transform_keys(hash2) {|other_key| ...} -> new_hash * hash.transform_keys -> new_enumerator * * Returns a new \Hash object; each entry has: * * A key provided by the block. * * The value from +self+. * + * An optional hash argument can be provided to map keys to new keys. + * Any key not given will be mapped using the provided block, + * or remain the same if no block is given. + * * Transform keys: * h = {foo: 0, bar: 1, baz: 2} * h1 = h.transform_keys {|key| key.to_s } * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2} * + * h.transform_keys(foo: :bar, bar: :foo) + * #=> {bar: 0, foo: 1, baz: 2} + * + * h.transform_keys(foo: :hello, &:to_s) + * #=> {:hello=>0, "bar"=>1, "baz"=>2} + * * Overwrites values for duplicate keys: * h = {foo: 0, bar: 1, baz: 2} * h1 = h.transform_keys {|key| :bat } @@ -3243,22 +3254,12 @@ static VALUE rb_hash_flatten(int argc, VALUE *argv, VALUE hash); /* * call-seq: * hash.transform_keys! {|key| ... } -> self + * hash.transform_keys!(hash2) -> self + * hash.transform_keys!(hash2) {|other_key| ...} -> self * hash.transform_keys! -> new_enumerator * - * Returns +self+ with new keys provided by the block: - * h = {foo: 0, bar: 1, baz: 2} - * h.transform_keys! {|key| key.to_s } # => {"foo"=>0, "bar"=>1, "baz"=>2} - * - * Overwrites values for duplicate keys: - * h = {foo: 0, bar: 1, baz: 2} - * h1 = h.transform_keys! {|key| :bat } - * h1 # => {:bat=>2} - * - * Returns a new \Enumerator if no block given: - * h = {foo: 0, bar: 1, baz: 2} - * e = h.transform_keys! # => #0, "bar"=>1, "baz"=>2}:transform_keys!> - * h1 = e.each { |key| key.to_s } - * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2} + * Same as Hash#transform_keys but modifies the receiver in place + * instead of returning a new hash. */ static VALUE rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash) -- cgit v1.2.3