Feature #6277

Hash#convert_key

Added by Thomas Sawyer about 2 years ago. Updated over 1 year ago.

[ruby-core:44270]
Status:Assigned
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:core
Target version:next minor

Description

=begin
Many times a hash with uniform keys is needed (or is at least preferable) for a particular usecase. To this end I propose ((%Hash#convert_key%)).

h = {}
h.convertkey{ |k| k.tosym }
h['a'] = 1
h.update('b'=>2)
h #=> {:a=>1, :b=>2}

The idea is similar in concept to ((%#default_proc%)).

Others solutions to fill this need have been tried and used, but almost exclusively are in the form of a new class. Most notable is Rails HashWithIndifferentAccess. But ((%#convert_key%)) has much greater flexibility since keys can be converted to anything.
=end

History

#1 Updated by Yusuke Endoh about 2 years ago

  • Status changed from Open to Assigned
  • Assignee set to Yukihiro Matsumoto

#2 Updated by Thomas Sawyer almost 2 years ago

It occurs to me that this issue could be solved in another way, via Subclassing. A subclass of Hash could be made with certain methods overridden to convert the keys as needed. This would offer complete flexibility (where as callbacks are limited). The only problem is, Ruby's Hash class is not very internally connascent --many different methods access the underlying data --there is no one, or few, specific methods that can be overridden to handle all cases. This leads to a very unDRY and bloated subclass.

If Ruby's Hash could be modified to follow essentially a CRUD model, with single points-of-entry for the creation, reading, updating and deletion of entries, and all other methods route through these core methods for access to the underlying data, then it would be easy enough to subclass and implement the key conversion behaviour.

#3 Updated by Thomas Sawyer almost 2 years ago

I am going to create a separate issue fro the CRUDify of Hash. After working on the Hashery (http://github.com/rubyworks/hashery) project all this week, it is clear to me that both a key casting proc and a CRUDified Hash class are independently useful.

#4 Updated by Yutaka HARA over 1 year ago

  • Target version changed from 2.0.0 to next minor

Also available in: Atom PDF