[#101179] Spectre Mitigations — Amel <amel.smajic@...>
Hi there!
5 messages
2020/12/01
[#101694] Ruby 3.0.0 Released — "NARUSE, Yui" <naruse@...>
V2UgYXJlIHBsZWFzZWQgdG8gYW5ub3VuY2UgdGhlIHJlbGVhc2Ugb2YgUnVieSAzLjAuMC4gRnJv
4 messages
2020/12/25
[ruby-core:101211] [Ruby master Feature#17342] Hash#fetch_set
From:
marcandre-ruby-core@...
Date:
2020-12-03 07:03:19 UTC
List:
ruby-core #101211
Issue #17342 has been updated by marcandre (Marc-Andre Lafortune).
I think this is a good feature. I like the fact that the this can not be implemented in pure Ruby as efficiently (i.e. with hash calculated once).
An alternative name is `fetch_init`, as it may gives a better idea that it is meant to initialize the value (once) for the key. That being said, `fetch_set` is not a good name too.
----------------------------------------
Feature #17342: Hash#fetch_set
https://bugs.ruby-lang.org/issues/17342#change-88896
* Author: MaxLap (Maxime Lapointe)
* Status: Open
* Priority: Normal
----------------------------------------
I would like to propose adding the `fetch_set` method to `Hash`. It behaves just like `fetch`, but when using the default value (2nd argument or the block), it also sets the value in the Hash for the given key.
We often use the pattern `cache[key] ||= calculation`. This pattern however has a problem when the calculation could return false or nil, as in those case, the calculation is repeated each time.
I believe the best practice in that case is:
```ruby
cache.fetch(key) { cache[key] = calculation }
```
With my suggestion, it would be:
```ruby
cache.fetch_set(key) { calculation }
```
In these examples, each part is very short, so the `fetch` case is still clean. But as each part gets longer, the need to repeat cache[key] becomes more friction.
Here is a more realistic example:
```ruby
# Also using the key argument to the block to avoid repeating the
# long symbol, adding some indirection
RequestStore.store.fetch(:monitor_value_is_delayed?) do |key|
RequestStore.store[key] = !MonitorValue.where('date >= ?', Time.now - 5.minutes).exists?
end
RequestStore.store.fetch_set(:monitor_value_is_delayed?) do
!MonitorValue.where('date >= ?', Time.now - 5.minutes).exists?
end
```
There is a precedent for such a method: Python has it, but with a quite confusing name: `setdefault(key, default_value)`. This does not set a default for the whole dictionary as the name would make you think, it really just does what is proposed here. https://docs.python.org/3/library/stdtypes.html#dict.setdefault
--
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>