Getting hash with symbol as keys for mongo in rails

前端 未结 2 1936
南笙
南笙 2021-01-18 20:07

The Mongo ruby driver seems to get put your results into a hash with strings as keys. Is there a way to tell it to convert the keys into symbols instead?

2条回答
  •  天命终不由人
    2021-01-18 20:38

    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"
    

提交回复
热议问题