From: eregontp@... Date: 2019-09-26T21:49:06+00:00 Subject: [ruby-core:95120] [Ruby master Feature#16183] Hash#with_default Issue #16183 has been updated by Eregon (Benoit Daloze). zverok (Victor Shepelev) wrote: > So, I propose side-effect-less method, that **is** acceptable for chaining, I believe. That means a copy of the Hash is necessary on each call to #with_default. I.e., it would be the same as: ```ruby h = {a: 1, b: 2} h2 = h.dup.tap { _1.default = 3 } ``` I think it's better to keep a potentially expensive copy of the Hash explicit with the `.dup` call + `default=`. But I agree there is some beauty to change the default value in a safe, non-mutable way with a single method call. ---------------------------------------- Feature #16183: Hash#with_default https://bugs.ruby-lang.org/issues/16183#change-81754 * 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: