Ruby : Accessing Hash keys as String or Symbol

You might have notices or not but if you define a Hash instace with keys in ‘String’ then you cannot access then via :symbol and vice-versa

To be more clear see the following code snippet

 c = {"first"=> 12, "second"=>13}
 => {"first"=>12, "second"=>13} 
 c[:first]
 => nil 
 c['first']
 => 12

 

Now how to access hash data regardless of data-type of key?

There are a few techniques but the One that is far simple and recommended and defaultly used by Rails is ActiveSupport::HashWithIndifferentAccess

rgb = ActiveSupport::HashWithIndifferentAccess.new
rgb[:black] = '#000000'
rgb[:black] # => '#000000'
rgb['black'] # => '#000000'
rgb['white'] = '#FFFFFF'
rgb[:white] # => '#FFFFFF'
rgb['white'] # => '#FFFFFF'




Sources:
http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html

 

 

Leave a comment