Project

General

Profile

Actions

Feature #20769

closed

Add `Hash#transform_value`

Added by seanpdoyle (Sean Doyle) about 2 months ago. Updated about 2 months ago.

Status:
Feedback
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

Like1
Like0Like1Like0