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

后端 未结 15 1835
不思量自难忘°
不思量自难忘° 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:37

    hash = {"apple" => "banana", "coconut" => "domino"}
    Hash[hash.map{ |k, v| [k.to_sym, v] }]
    #=> {:apple=>"banana", :coconut=>"domino"}
    

    @mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent to_sym, just want to remind that in Ruby 1.8 1.to_sym == nil, so playing with some key types can be misleading):

    hash = {"a" => {"b" => "c"}, "d" => "e", Object.new => "g"}
    
    s2s = 
      lambda do |h| 
        Hash === h ? 
          Hash[
            h.map do |k, v| 
              [k.respond_to?(:to_sym) ? k.to_sym : k, s2s[v]] 
            end 
          ] : h 
      end
    
    s2s[hash] #=> {:d=>"e", #=>"g", :a=>{:b=>"c"}}
    

提交回复
热议问题