[ruby-core:96522] [Ruby master Bug#16457] Invisible keys on hash when defining hash with Hash.new({})
[email protected] Fri, 27 Dec 2019 19:54:39 +0000 (UTC)
| Newsgroups | gmane.comp.lang.ruby.core |
|---|---|
| Message-ID | <redmine.journal-83453.20191227195438.f9996863e5899d14@ruby-lang.org> |
Issue #16457 has been updated by marcandre (Marc-Andre Lafortune).
Status changed from Open to Rejected
This is as per spec.
You typically never want a hash's default to be mutable. Try to name that default in your head (e.g. `X={}; my_hash= Hash.new(X)`, this might help understand it.
You may want to do instead: `Hash.new{ |h, k| h[k] = {} }` which creates a new hash for every key.
Further questions are probably better asked on StackOverflow or similar.
----------------------------------------
Bug #16457: Invisible keys on hash when defining hash with Hash.new({})
https://bugs.ruby-lang.org/issues/16457#change-83453
* Author: Farhad (Farhad Eyvazli)
* Status: Rejected
* Priority: Normal
* Assignee:
* Target version:
* ruby -v: 2.6.3
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN
----------------------------------------
When using ``` Hash.new()``` to initialize a hash, we all know for undefined it will return specific value which sent as a parameter to the ```Hash.new``
But when doing something like that keys get invisible
```ruby
my_hash: Hash.new({})
my_hasy[:my_key] #=> {}
my_hash[:my_key].merge!(value: '')
my_hash.keys #=> []
my_hash.fetch(:my_key) #=> KeyError: key not found: :my_key
my_hash.dig(:my_key) #=> {:value=>""}
my_hash[:my_key] #=> {:value=>""}
```
Maybe it's normal behavior because, for each missing key, it initialize new empty has and merge it to that. But I'm not sure it can cause a memory leak or not when removing the main hash (:my_hash)
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>