Issue #14580 has been updated by Soilent (Konstantin x).


Hanmac (Hans Mackowiak) wrote:
> ~~~ ruby
> hash.transform_values(:a, :b) { |val| val + 42 }
> hash[:a] #=> 44
> ~~~
> 
> what about the b key? should it:
> a) throw exception
> b) gives `nil` to the block ? which your code would be an `NoMethod + for nil`
> c) will be skipped

Thanks for the question.

I think that `hash.store(:b)` should yield the default value if the key does not exist, i.e. option b.
But in case of `hash.transform_values(:a, :b)`, when we want to update several keys, it is best to skip non-existent keys (option c)


----------------------------------------
Feature #14580: Hash#store accepts a block
https://bugs.ruby-lang.org/issues/14580#change-70847

* Author: Soilent (Konstantin x)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
Given a hash

~~~ ruby
hash = { a: 2 }
~~~

I want to update a single value in the hash:

~~~ ruby
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.

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

Or it can be something like this:

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



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>