Last Updated: February 25, 2016
·
740
· rshetty

Symbolizing the keys of your Hash using "inject"

I recently came across this awesome ruby "inject" method which is widely used in rails and ruby world to symbolize the keys of your hash.

So here I will present an example on how to achieve that. This can be added as an helper function to your application and used wherever and whenever required.

Symbolizing the keys of your hash :

def symbolize_keys hash
  hash.inject({}) { options ,(k,v) | options[k.to_sym] = v; options}
end

This function takes a hash iterates over the hash, gets the keys and coverts them into ruby symbols.

INPUT : { "a" => "b" }
OUTPUT : { :a => "b" }

Happy Hacking !!!!