Hash key formatter

Add an attribute to Hash to store transformation of keys. For instance:

h = Hash.new
h.key_format do |k|

h[‘BIG’] = 10
h #=> { :big => 10 }

Good little RCR.

On 5/11/06, [email protected] [email protected] wrote:

Add an attribute to Hash to store transformation of keys.

I like the idea. Here’s a simple-minded implementation:

class Hash
def key_format(&block)
@key_format ||= proc {|x| x}
@key_format = block_given? ? block : @key_format

look ma! no aliases (but less efficient)

prev_store = instance_method(:store)
define_method :store do |key, value|
prev_store.bind(self).call(key_format.call(key), value)

def []=(key, value)
store(key, value)

h = Hash.new

h[:a] = 1
p h

h[‘A’] = 1,2,3
p h
p h.key_format

f = Hash.new
f.key_format {|key| key.to_s.downcase.to_sym }

f[:a] = 1
p f

f[‘A’] = 1,2,3
p f

p f.key_format

---------- Ruby ----------
{“A”=>[1, 2, 3], :a=>1}
#Proc:[email protected]:/rubylib/experiments/hash-format-key.rb:3
{:a=>[1, 2, 3]}
#Proc:[email protected]:/rubylib/experiments/hash-format-key.rb:29

Output completed (0 sec consumed) - Normal Termination

I’m just playing with the idea of avoiding aliases - I’d probably use
a GUID alias in production to avoid the overhead of rebinding the old
:store method on every store.


[email protected] wrote:

Good little RCR.
Hm, Hash::MixIn already supports this for hash-like classes. See

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs