Project

General

Profile

Feature #13583

Updated by graywolf (Gray Wolf) 8 months ago

In 2.4, new useful method `Hash#transform_values` was added. I would like to propose also adding matching method `Hash#transform_keys`.

```ruby
{a: 1, b: 2}.transform_keys { |k| k.to_s }
=> {"a"=>1, "b"=>2}
```

What needs need to be considered is what to do in case of two keys mapping to the same new value

```ruby
{ a: 1, b: 2 }.transform_keys {|_| :same_key } # what should happen?
```

I think using `Hash[]` as model behaviour is a good idea.

```ruby
Hash[{ a: 1, b: 2 }.map { |key, value| [:s, value] }]
=> {:s=>2}
```

it's also how have `Hash#transform_keys` works work in rails (afaict).

This is follow up feature request to #9970, which seems to be stalled. If the behaviour can be agreed upon, I can try putting together a patch (if no one else want to step up).

Back