ActiveSupport Option Hashes

A small blog item, for remembering this method…

When using a (normal) Hash in Ruby on Rails accessing an element with a symbol key or string key results in a different item.

(Notice the use of a string and symbol to access a key)

normal = {'foo'=>"lish"} 
normal[:foo] = 'bar'

results in the hash:

{"foo"=>"lish", :foo=>"bar"}

To solve this issue you can convert every Hash to HashWithInDifferentAccess

special = {'foo'=>'lish'}.with_indifferent_access
special[:foo] = 'bar'

Results in

special.class => ActiveSupport::HashWithIndifferentAccess

that more like it :-)