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.

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

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

results in the hash:

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

To solve this issue you can convert every Hash to HashWithInDifferentAccess

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

Results in

1
{"foo"=>"bar"}
1
special.class => ActiveSupport::HashWithIndifferentAccess

that more like it :-)