From: konstantin@... Date: 2018-03-08T11:59:37+00:00 Subject: [ruby-core:86049] [Ruby trunk Feature#14580] Hash#store accepts a block Issue #14580 has been updated by Soilent (Konstantin x). Eregon (Benoit Daloze) wrote: > Soilent (Konstantin x) wrote: > > Consider another example `hash.store(:time) { |ts| Time.parse(ts) }` > > That looks weird to me. > Either the Hash is caching String to Time, and then it should use > > ~~~ruby > Hash.new { |h,k| h[k] = Time.parse(k) } > ~~~ > > or it contains other data and then there seems to be little reason to first store a String for key :time and then only later parse it to a Time instance. I see your point, but the example was not about String to Time caching. Let's say you receive an HTTP POST request with the body `timestamp=2018-03-08T11:24:44Z&temperature=27`. You might want to validate the request and store it in a database: ~~~ruby begin params.store(:temperature) { |tm| Integer(tm) } params.store(:timestamp) { |ts| Time.parse(ts) } rescue ArgumentError => err # Invalid request, send response with status 422 or 400 end # Do something with `params` db[:events].insert(params) ~~~ I think that Hash#store with a block arg looks quite natural with the rest of the methods from the Hash API. ---------------------------------------- Feature #14580: Hash#store accepts a block https://bugs.ruby-lang.org/issues/14580#change-70913 * 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: