Forum: Ruby Hash key formatter

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2006-05-11 21:09
(Received via mailing list)
Add an attribute to Hash to store transformation of keys. For instance:

  h =
  h.key_format do |k|

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

Good little RCR.
Sean O. (Guest)
on 2006-05-12 03:18
(Received via mailing list)
On 5/11/06, removed_email_address@domain.invalid 
<removed_email_address@domain.invalid> 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(, value)

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

h =

h[:a] = 1
p h

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

f =
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}
{:a=>[1, 2, 3]}

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.

Florian GroÃ? (Guest)
on 2006-05-13 18:18
(Received via mailing list)
removed_email_address@domain.invalid wrote:

> Good little RCR.
Hm, Hash::MixIn already supports this for hash-like classes. See
This topic is locked and can not be replied to.