On 5/11/06, transfire / gmail.com <transfire / gmail.com> 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
  end

  # 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)
  end

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

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}
{"A"=>[1, 2, 3], :a=>1}
#<Proc:0x02886ca0@C:/rubylib/experiments/hash-format-key.rb:3>
{:a=>1}
{:a=>[1, 2, 3]}
#<Proc:0x02885c38@C:/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.

Regards,
Sean