Issue #16183 has been updated by zverok (Victor Shepelev).


> That means a copy of the Hash is necessary on each call to `#with_default`.

Yes, the same way it is for, say, `merge`, and we still use it in a lot of cases even when source hash would be dropped -- for the sake of chainability:

```ruby
FONTS = {body: 'Tahoma'}.merge(OS_FONTS.fetch(current_os)).merge(Settings.custom_fonts).freeze
```
 one may argue that it is tragically ineffective, but for the cases like this we just ignore it.

So I believe it is reasonable that something like:
```ruby
def render(settings, values)
  render_widget(settings[:type], settings[:name], values.with_default('<empty>'))
end
```
I believe from this code it is obvious that `values` parameter is not altered (and so call site wouldn't be surprised), and passed further is its copy with some reasonable default value that makes sense for UI.

For a lot of features, we have both chainable (copying) and non-chainable (destructive, inplace) version, why not for one of the Hash's usefulest features?..

----------------------------------------
Feature #16183: Hash#with_default
https://bugs.ruby-lang.org/issues/16183#change-81760

* Author: zverok (Victor Shepelev)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
Reasons: there is no way, currently, to *declaratively* define Hash with default value (for example, to store it in constant, or use in an expression). Which leads to code more or less like this:


```ruby
FONTS = {
  title: 'Arial',
  body: 'Times New Roman',
  blockquote: 'Tahoma'
}.tap { |h| h.default = 'Courier' }.freeze

# Grouping indexes:
ary.each_with_object(Hash.new { |h, k| h[k] = [] }).with_index { |(el, h), idx| h[el.downcase] << idx }
```

With proposed method:
```ruby
FONTS = {
  title: 'Arial',
  body: 'Times New Roman',
  blockquote: 'Tahoma'
}.with_default('Courier').freeze

ary.each_with_object({}.with_default { [] }).with_index { |(el, h), idx| h[el.downcase] << idx }
```

About the block synopsys: I am not 100% sure, but I believe that _most_ of the time when `default_proc` provided, it looks like `{ |h, k| h[k] = some_calculation }`. So, I believe for this "declarative simplification" of defaults, it is acceptable to assume it as the only behavior (pass only key to block, and always store block's result); more flexible form would still be accessible with `Hash.new`.



-- 
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>