# Hash key formatter

**URL:** <https://www.ruby-forum.com/t/hash-key-formatter/94706>\
**Category:** Ruby\
**Created:** [May 11, 2006, 7:09pm UTC](https://www.ruby-forum.com/t/hash-key-formatter/94706 "2006-05-11T19:09:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 11, 2006, 7:09pm UTC](https://www.ruby-forum.com/t/hash-key-formatter/94706/1 "2006-05-11T19:09:37Z")

</div>

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

h = Hash.new  
h.key\_format do |k|  
k.to\_s.downcase.to\_sym  
}

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

Good little RCR.

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 12, 2006, 1:18am UTC](https://www.ruby-forum.com/t/hash-key-formatter/94706/2 "2006-05-12T01:18:41Z")

</div>

On 5/11/06, removed\_email\_address@domain.invalid [removed\_email\_address@domain.invalid](mailto: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  
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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 13, 2006, 4:18pm UTC](https://www.ruby-forum.com/t/hash-key-formatter/94706/3 "2006-05-13T16:18:55Z")

</div>

removed\_email\_address@domain.invalid wrote:

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