Project

General

Profile

Actions

Feature #20769

open

Add `Hash#transform_value`

Added by seanpdoyle (Sean Doyle) 2 days ago. Updated 1 day ago.

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

Description

Add Hash#transform_value as a specialized, key-specific version of Hash#transform_values.

hash = { image: "https://example.com/image.jpg" }
mutated_hash = hash.transform_value(:image) { |url| download(url) }

hash # => { image: "https://example.com/image.jpg" }
mutated_hash # => { image: File<...> }

hash.transform_value!(:image) { |url| download(url) }
hash # => { image: File<...> }

Similar value transformation can be achieved through variable assignment and direct mutation:

hash = { image: "https://example.com/image.jpg" }

hash.merge(image: download(hash[:image]))

hash[:image] = download(hash[:image])

While simple and currently supported, it requires a local variable (and therefore poses some challenges when chaining other methods) and repeats the Hash key in both the reading and writing portions of the code.

Actions

Also available in: Atom PDF

Like0
Like0Like0