Project

General

Profile

Actions

Feature #11761

closed

`Hash#default_set` and `Hash#default_proc_set`

Added by sawa (Tsuyoshi Sawada) almost 9 years ago. Updated almost 9 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:71794]

Description

I often want to assign a default value or proc to an existing hash h and chain method after it. The way I do it is:

Hash.new(default_value).merge(h)...
Hash.new{default_proc_value}.merge(h)...

It would be convenient if I can assign them to a hash directly, and Hash#default= and Hash#default_proc= are close to doing that, but they are actually not useful because the return value is not the receiver hash:

h.default = default_value; h...
h.default_proc = proc {default_proc_value}; h...

I wish there were methods Hash#default_set and Hash#default_proc_set that return the receiver hash:

h.default_set(default_value)...
h.default_proc_set{default_proc_value}...

Updated by sawa (Tsuyoshi Sawada) almost 9 years ago

Or, perhaps there should be just one method Hash#default_set that can take either an argument or a block:

h.default_set(default_value)...
h.default_set{default_proc_value}...

Updated by nobu (Nobuyoshi Nakada) almost 9 years ago

Kernel#tap has been added for such purpose, I think.

Updated by Eregon (Benoit Daloze) almost 9 years ago

Resetting the default value/proc for a Hash multiple times seems a rather special case, could you illustrate why you want to do this?

Hash#merge is not affected by the default values, isn't it?

If it's more like Python setdefault, then I guess (h[k] ||= v).do_sth can work without changing globally the Hash default.

Updated by matz (Yukihiro Matsumoto) almost 9 years ago

  • Status changed from Open to Rejected

Use tap. Methods with side-effect should be handled with care. Making it chainable has little benefit.

Matz.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0