Getting hash with symbol as keys for mongo in rails
The Mongo ruby driver seems to get 开发者_Go百科put your results into a hash with strings as keys. Is there a way to tell it to convert the keys into symbols instead?
According to the FAQ, Even though there is a symbol type in Mongo, and you can store symbols in values, the BSON format specifies that keys must be strings.
If you have a Hash
that is keyed with strings, and you want to be able to use Symbol
s as keys to access its values, you can use a HashWithIndifferentAccess
. If you are not using Rails, you can get this class via the ActiveSupport
gem.
my_hash = { 'name' => 'Joe', 'email' => 'joe@schmoe.com' }
my_hash = HashWithIndifferentAccess.new my_hash
puts my_hash[:name] # "Joe"
精彩评论