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

后端 未结 15 1793
不思量自难忘°
不思量自难忘° 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条回答
  • 2020-12-04 19:44

    Starting with Ruby 2.5 you can use the transform_key method.

    So in your case it would be:

    h = { "id" => "123", "name" => "test" }
    h.transform_keys!(&:to_sym)      #=> {:id=>"123", :name=>"test"}
    

    Note: the same methods are also available on Ruby on Rails.

    0 讨论(0)
  • 2020-12-04 19:50

    Try this:

    hash = {"apple" => "banana", "coconut" => "domino"}
     # => {"apple"=>"banana", "coconut"=>"domino"} 
    
    hash.tap do |h|
      h.keys.each { |k| h[k.to_sym] = h.delete(k) }
    end
     # => {:apple=>"banana", :coconut=>"domino"} 
    

    This iterates over the keys, and for each one, it deletes the stringified key and assigns its value to the symbolized key.

    0 讨论(0)
  • 2020-12-04 19:52

    If you're using Rails (or just Active Support):

    { "id" => "123", "name" => "test" }.symbolize_keys
    
    0 讨论(0)
提交回复
热议问题