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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s