How do I convert a Ruby hash so that all of its keys are symbols?

后端 未结 15 1813
不思量自难忘°
不思量自难忘° 2020-12-04 19:01

I have a Ruby hash which looks like:

{ \"id\" => \"123\", \"name\" => \"test\" }

I would like to convert it to:

{ :id         


        
15条回答
  •  Happy的楠姐
    2020-12-04 19:34

    Facets' Hash#rekey is also a worth mentioning.

    Sample:

    require 'facets/hash/rekey'
    { "id" => "123", "name" => "test" }.deep_rekey
    => {:id=>"123", :name=>"test"}
    

    There is also a recursive version:

    require 'facets/hash/deep_rekey'
    { "id" => "123", "name" => {"first" => "John", "last" => "Doe" } }.deep_rekey
    => {:id=>"123", :name=>{:first=>"John", :last=>"Doe"}}
    

提交回复
热议问题