Issue #16274 has been updated by duerst (Martin D=FCrst).


matz (Yukihiro Matsumoto) wrote:

> FYI, we do not accept a similar change to `transform_values`.

Matz - Do you mean "we reject a similar change to `transform_values`", or d=
o you mean "we have not yet accepted a similar change to `transform_values`=
 (but could consider it later)"?

----------------------------------------
Feature #16274: Transform hash keys by a hash
https://bugs.ruby-lang.org/issues/16274#change-83340

* Author: sawa (Tsuyoshi Sawada)
* Status: Open
* Priority: Normal
* Assignee: =

* Target version: 2.8
----------------------------------------
We have `Hash#transform_keys` and its bang version to change the keys of a =
hash, but that requires passing a block, which assumes that the mapping fro=
m the old keys to the new keys follows some rule. But in reality, we freque=
ntly want to change the keys where it is difficult to provide a rule. For e=
xample, suppose we have:

```
hash =3D {created: 2019-10-23 17:54:46 +0900, updated: 2019-10-23 17:59:18 =
+0900, author: "foo"}
```

and want to achieve:

```
{created_at: 2019-10-23 17:54:46 +0900, update_time: 2019-10-23 17:59:18 +0=
900, author: "foo"}
```


I request an option to change the keys of a hash not by giving a block, but=
 by passing a hash. I came up with two options.

### 1. Argument for `Hash#transform_keys` and its bang version

Allow `Hash#transform_keys` to optionally take a hash argument instead of a=
 block.

```
hash.transform_keys({created: :created_at, updated: :update_time})
# =3D> {created_at: 2019-10-23 17:54:46 +0900, update_time: 2019-10-23 17:5=
9:18 +0900, author: "foo"}
```

### 2. Argument for `Hash#slice` and the counterparts in other classes

Since `Hash#slice` is often the first step of modifying a hash into some ot=
her hash form, it makes sense to let it take an optional hash argument.

```
hash.slice(:created, :author, transform_keys: {created: :created_at})
# =3D> {created_at: 2019-10-23 17:54:46 +0900, author: "foo"}
```


With option 1, it could make sense to even allow a hash argument and a bloc=
k simultaneously:

```
hash.transform_keys({created: :created_at, updated: :update_time}, &:to_s)
# =3D> {"created_at" =3D> 2019-10-23 17:54:46 +0900, "update_time" =3D> 201=
9-10-23 17:59:18 +0900, "author" =3D> "foo"}
```




-- =

https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=3Dunsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>