Project

General

Profile

Actions

Feature #14580

open

Hash#store accepts a block

Added by Soilent (Konstantin x) about 6 years ago. Updated about 6 years ago.

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

Description

Given a hash

hash = { a: 2 }

I want to update a single value in the hash:

hash[:a] = hash[:a] + 42
hash[:a] #=> 44

But instead, I would like to have a method that yields the current value for a given key and associates the block result with the key (similar to Hash#update). I think that Hash#store can be extended to support a block arg.

hash.store(:a) { |val| val + 42 }
hash[:a] #=> 44

Or it can be something like this:

hash.transform_values(:a, :b) { |val| val + 42 }
hash[:a] #=> 44
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0