🖥

Rails | Convert all hash keys to symbols (symbolized_keys / deep_symbo

2019/04/16に公開

As the title.

 { 'a' => 1, 'b' => 2, 'c' => 3 }.symbolize_keys # => {:a=>1, :b=>2, :c=>3} 

When the hierarchy of hash is deep

deep_symbolize_keys it is deep_symbolize_keys , it will change to all symbols regardless of the hierarchy. (Rails 4)

 { 'a' => 1, 'b' => 2, 'c' => { 'd' => 3 } }.deep_symbolize_keys # => {:a=>1, :b=>2, :c=>{:d=>3}} 

Great symbolize deep symbolize keys

deep_symbolize_keys , for example, even if there is an array in the middle, it does not matter.

 {'a' => 1, 'b' => 2, 'c' => [{'d' => [ { 'e' => 3 }] } ] }.deep_symbolize_keys # => {:a=>1, :b=>2, :c=>[{:d=>[{:e=>3}]}]} 

Supplement

  • There is also a destructive method. ( symbolize_keys / deep_symbolize_keys! )
  • I posted it because I didn't hit it with "Rails / All / Symbols".

environment

  • Rails 4.2.6

Original by

Rails | ハッシュのキーを全てシンボルに変える ( symbolized_keys / deep_symbolize_keys )

About

About this translattion

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion