Home > other >  How do I prevent string keys from being converted to symbols in Rails?
How do I prevent string keys from being converted to symbols in Rails?

Time:09-30

I'm using Rails 4.2. I noticed when I try and create an array of hashes, it seems my string keys are getting converted to symbols ...

> my_hash_arr = [{"name": "DA", "amount": 100000 }]
=> [{:name=>"DA", :amount=>100000}]

I don't want this. I want my key "name", to remain as a string and not be converted to a symbol key. How do I structure my array so this conversion doesn't take place.

CodePudding user response:

deep_transform_keys is available from Rails 4.

From the documentation:

hash = { person: { name: 'Rob', age: '28' } }

hash.deep_transform_keys { |key| key.to_s }
# => { "person" => { "name" => "Rob", "age" => "28" } }

Or a more succinct version:

hash.deep_transform_keys(&:to_s)

CodePudding user response:

If you want that, the correct syntax is changing : to => like this:

 my_hash_arr = [{"name" => "DA", "amount" => 100000 }]
=> [{"name"=>"DA", "amount"=>100000}]
  • Related