Feature #6277



Added by trans (Thomas Sawyer) over 11 years ago. Updated almost 6 years ago.

Target version:


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 #=> {: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.

Updated by mame (Yusuke Endoh) over 11 years ago

  • Status changed from Open to Assigned
  • Assignee set to matz (Yukihiro Matsumoto)

Updated by trans (Thomas Sawyer) over 11 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 11 years ago

I am going to create a separate issue fro the CRUDify of Hash. After working on the 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) about 11 years ago

  • Target version changed from 2.0.0 to 2.6
Actions #5

Updated by naruse (Yui NARUSE) almost 6 years ago

  • Target version deleted (2.6)

Also available in: Atom PDF