From: "matheusrich (Matheus Richard) via ruby-core" Date: 2024-02-27T16:42:48+00:00 Subject: [ruby-core:116973] [Ruby master Feature#20300] Hash: set value and get pre-existing value in one call Issue #20300 has been updated by matheusrich (Matheus Richard). Rust [calls this method `insert`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.insert): > Inserts a key-value pair into the map. > > If the map did not have this key present, None is returned. > > If the map did have this key present, the value is updated, and the old value is returned. > > ```rs > let mut map = HashMap::new(); > assert_eq!(map.insert(37, "a"), None); > assert_eq!(map.is_empty(), false); > > map.insert(37, "b"); > assert_eq!(map.insert(37, "c"), Some("b")); > assert_eq!(map[&37], "c"); > ``` ---------------------------------------- Feature #20300: Hash: set value and get pre-existing value in one call https://bugs.ruby-lang.org/issues/20300#change-107020 * Author: AMomchilov (Alexander Momchilov) * Status: Open ---------------------------------------- When using a Hash, sometimes you want to set a new value, **and** see what was already there. Today, you **have** to do this in two steps: ```ruby h = { k: "old value" } # 1. Do a look-up for `:k`. old_value = h[:k] # 2. Do another look-up for `:k`, even though we just did that! h[:k] = "new value" use(old_value) ``` This requires two separate `Hash` look-ups for `:k`. This is fine for symbols, but is expensive if computing `#hash` or `#eql?` is expensive for the key. It's impossible to work around this today from pure Ruby code. One example use case is `Set#add?`. See https://bugs.ruby-lang.org/issues/20301 for more details. I propose adding `Hash#update_value`, which has semantics are similar to this Ruby snippet: ```ruby class Hash # Exact method name TBD. def update_value(key, new_value) old_value = self[key] self[key] = new_value old_value end end ``` ... except it'll be implemented in C, with modifications to `tbl_update` that achieves this with a hash-lookup. I'm opening to alternative name suggestions. @nobu came up with `exchange_value`, which I think is great. Here's a PR with a PoC implementation: https://github.com/ruby/ruby/pull/10092 ```ruby h = { k: "old value" } # Does only a single hash look-up old_value = h.update_value(:k, "new value") use(old_value) ``` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/