开发者

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 Symbols 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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜