Feature #6277
openHash#convert_key
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.convert_key{ |k| k.to_sym }
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
Updated by mame (Yusuke Endoh) over 12 years ago
- Status changed from Open to Assigned
- Assignee set to matz (Yukihiro Matsumoto)
Updated by trans (Thomas Sawyer) over 12 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.
Updated by trans (Thomas Sawyer) over 12 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.
Updated by yhara (Yutaka HARA) almost 12 years ago
- Target version changed from 2.0.0 to 2.6