Project

General

Profile

Actions

Feature #21182

open

Add Hash#rename

Added by calebm (Caleb Meyer) about 12 hours ago. Updated about 2 hours ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:121299]

Description

Abstract: Implement Hash#rename which takes as arguments a from key and a to key and renames the from key to the new name.

Background: One of the most common data transformations for a hash (in my experience) is renaming a single key. You can do this with the existing hash methods (e.g. hash['new'] = hash.delete('old') or hash.transform_keys('old' => 'new')) but they feel a bit clunky.

Proposal:

Add a new method to Hash, something like this:

class Hash
  # usage { old: 'value' }.rename(:old, to: :new)
  # => { new: 'value' }
  def rename(from, to:)
    transform_keys(from => to)
  end

  def rename!(from, to:)
    transform_keys!(from => to)
  end
end

Updated by nobu (Nobuyoshi Nakada) about 2 hours ago

transform_keys('old' => 'new') feels good enough.
At least, ('old' => 'new') (or even ('old', 'new'), (from: 'old', to: 'new')) looks clearer than (:old, to: :new) to me.

And another concern is if the method name rename express the semantics well.
Is there a consensus that name means key?

Actions

Also available in: Atom PDF

Like0
Like0